The nose testing framework (for python) supports dynamically generating test cases at run-time (the following, from the documentation, results in five distinct test cases):
def test_evens(): for i in range(0, 5): yield check_even, i, i*3 def check_even(n, nn): assert n % 2 == 0 or nn % 2 == 0
How can I achieve this result using javascript frameworks such as mocha or qunit? (I am not attached to any particular framework at this point.)
My use-case is writing a test runner to monitor several items on an external server. I would provide a list of resource URLs. Each test attempts to poll that resource and returns success or failure depending on what it finds. I have a prototype built in python (using nose) but would like to implement in node.js if I can. Eventually, this would be included in a CI setup.
If you've ever written tests for a Node. js application, chances are you used an external library. However, you don't need a library to run unit tests in Javascript.
Jest. Jest is a testing framework developed by Facebook. Originally designed to make UI testing easier for React developers, it's now a full standalone suite of tools for any type of JavaScript project (including Node. js) and includes features such as a built-in assertion library, code coverage, and mocking.
Yes you can dynamically created test suites with cases using Mocha. I have installed mocha globally npm install -g mocha
and I use should.
var should = require('should'); var foo = 'bar'; ['nl', 'fr', 'de'].forEach(function(arrElement) { describe(arrElement + ' suite', function() { it('This thing should behave like this', function(done) { foo.should.be.a.String(); done(); }); it('That thing should behave like that', function(done) { foo.should.have.length(3); done(); }); }); });
If you want to dynamically create It()
tests using data obtained asynchronously, you can (ab)use the before()
hook with a placeholder It()
test to ensure mocha waits until before()
is run. Here's the example from my answer to a related question, for convenience:
before(function () { console.log('Let the abuse begin...'); return promiseFn(). then(function (testSuite) { describe('here are some dynamic It() tests', function () { testSuite.specs.forEach(function (spec) { it(spec.description, function () { var actualResult = runMyTest(spec); assert.equal(actualResult, spec.expectedResult); }); }); }); }); }); it('This is a required placeholder to allow before() to work', function () { console.log('Mocha should not require this hack IMHO'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With