Alcadur
Alcadur

Reputation: 685

Mocha, Chai - loop in test

How should I write unit test for function which should test: 50 < n < 100? Is there better way than loop in test? Can I pass arguments to test function to generate test case based on that arguments? ex.

it('should return $n+1', function(n){
  expect(add(n)).to.be.eql(n+1);
},[ 1, 2, 3])

and it should show result as 3 different tests:

should return 1+1
should return 2+1
should return 3+1

https://plnkr.co/edit/HBJP46lyTbBkH4Pclu2S

Upvotes: 4

Views: 8431

Answers (1)

robertklep
robertklep

Reputation: 203519

If you're using Mocha:

[ 1, 2, 3 ].forEach(value => {
  it(`should return ${ value }+1`, () => {
    expect(add(value)).to.be.eql(value + 1);
  })
});

// The same, but for older versions of Node.js/browser:
[ 1, 2, 3 ].forEach(function(value) {
  it('should return ' + value + '+1', function() {
    expect(add(value)).to.be.eql(value + 1);
  })
});

Upvotes: 8

Related Questions