-->

What is describe() in Mocha

2020-08-20 08:55发布

问题:

I am trying to get my hands dirty with Mocha and here is the example I saw from documentation:

var assert = require("assert")
describe('Array', function(){
  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    })
  })
})

Most of the examples show the second describe statement

  describe('#indexOf()', function(){

starting with # in #indexOf(). What is the significance of this #? Why can this not be written simply as indexOf? Where can I get a fundamental understanding of how the describe works?

PS: I looked at the documentation at http://visionmedia.github.io/mocha/#interfaces but can't figure out how these came into picture and how are these interfaces processed.

Thx

回答1:

the bdd syntax of mocha is a inspired in ruby's RSpec, therefore you'd find the best tips for mocha's conventions searching for RSpec, here's a good place to start:

http://betterspecs.org/

In particular the # is mentioned there:

For instance, use the Ruby documentation convention of . (or ::) when referring to a class method's name and # when referring to an instance method's name.



回答2:

Looking at the source code of Mocha, I don't see it doing anything significant with a # appearing in the first parameter of describe.

This being said, in some documentation systems for JavaScript (for instance, jsdoc), the use of a # indicates that what follows belongs to an object instance, rather than to the object's class. So Foo#bar would be something you could call like this:

var foo = new Foo();
foo.bar(...);

Not like this:

Foo.bar(...)

The latter would be represented as Foo.bar. So it would make sense in a test suite to use the same kind of notation to distinguish whether the methods being tested belong to instances or classes.



回答3:

starting with # in #indexOf(). What is the significance of this #?

None. Some people think that it looks better.

Where can I get a fundamental understanding of how the describe works?

It's basically a way to group your tests together and run before/after for a group of tests.

You'll know when you need it, and if you're asking this question, you can safely ignore all describe's and write tests without them.