Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 655
neezer Avatar asked Jul 06 '12 23:07

neezer


People also ask

Can mocha rerun tests?

Retrying Mocha tests Mocha provides a this. retries() function that allows you specify the number of times a failed test can be retried. For each retry, Mocha reruns the beforeEach() and afterEach() Hooks but not the before() and after() Hooks.

Do mocha tests run sequentially?

According to it, tests are run synchronously. This only shows that ordered code is run in order. That doesn't happen by accident.

Does mocha run tests in parallel?

Mocha does not run individual tests in parallel. That means if you hand Mocha a single, lonely test file, it will spawn a single worker process, and that worker process will run the file. If you only have one test file, you'll be penalized for using parallel mode. Don't do that.

Is mocha a runner test?

Mocha is one of the most popular testing frameworks for JavaScript. In particular, Mocha has been the test runner of choice in the Node.


2 Answers

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));
            })
        })
    })
})
like image 109
HackerBamboo Avatar answered Oct 05 '22 06:10

HackerBamboo


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.

like image 26
Steve McGuire Avatar answered Oct 05 '22 06:10

Steve McGuire