neezer
neezer

Reputation: 20560

Loop Mocha tests?

I'm trying to loop a mocha test suite (I want to test my system against a myriad of values with expected results), but I can't get it to work. For example:

spec/example_spec.coffee:

test_values = ["one", "two", "three"]

for value in test_values
  describe "TestSuite", ->
    it "does some test", ->
      console.log value
      true.should.be.ok

The problem is that my console log output looks like this:

three
three
three

Where I want it to look like this:

one
two
three

How can I loop over these values for my mocha tests?

Upvotes: 12

Views: 8358

Answers (2)

HackerBamboo
HackerBamboo

Reputation: 31

You can use 'data-driven'. https://github.com/fluentsoftware/data-driven

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

Upvotes: 3

Steve McGuire
Steve McGuire

Reputation: 1477

The issue here is that you're closing over the "value" variable, and so it will always evaluate to whatever its last value is.

Something like this would work:

test_values = ["one", "two", "three"]
for value in test_values
  do (value) ->
    describe "TestSuite", ->
      it "does some test", ->
        console.log value
        true.should.be.ok

This works because when value is passed into this anonymous function, it is copied to the new value parameter in the outer function, and is therefore not changed by the loop.

Edit: Added coffeescript "do" niceness.

Upvotes: 13

Related Questions