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.
Yes you can dynamically created test suites with cases using Mocha. I have installed mocha globally
npm install -g mocha
and I use should.With Mocha 1.21.4, you can create suite/test at runtime in following way.
See https://gist.github.com/cybertk/fff8992e12a7655157ed for more details
If you want to dynamically create
It()
tests using data obtained asynchronously, you can (ab)use thebefore()
hook with a placeholderIt()
test to ensure mocha waits untilbefore()
is run. Here's the example from my answer to a related question, for convenience:You can accomplish this by updating the tests property manually after the response is returned from the async method:
This doesn't use dynamic describes etc, just updates the current describe block before the main tests run!
Yep! Brilliant advice from Quanlong!
Here is my example of dynamic test generation with Node's readline module:
It's worth noting that in addition to the accepted answer above, mocha's docs now include an example of how to achieve this. I've reproduced it below for posterity.