I'm looking for a way to run async code before the entire mocha test.
Here's an example of a test that uses an array of arguments & expectations and loops over all of the items in this array to produce function assertions.
var assert = require('assert')
/* global describe, it*/
var fn = function (value) {
return value + ' ' + 'pancake'
}
var tests = [
{
'arg': 'kitty',
'expect': 'kitty pancake'
},
{
'arg': 'doggy',
'expect': 'doggy pancake'
},
]
describe('example', function () {
tests.forEach(function (test) {
it('should return ' + test.expect, function (){
var value = fn(test.arg)
assert.equal(value, test.expect)
})
})
})
Now, my question is how would this work if the tests value came from a promise, like this:
var assert = require('assert')
var Promise = require('bluebird')
/* global describe, it*/
var fn = function (value) {
return value + ' ' + 'pancake'
}
function getTests () {
return Promise.resolve('kitty pancake')
.delay(500)
.then(function (value) {
return [
{
'arg': 'kitty',
'expect': value
},
{
'arg': 'doggy',
'expect': 'doggy pancake'
}
]
})
}
getTests().then(function (tests) {
describe('example', function () {
tests.forEach(function (test) {
it('should return ' + test.expect, function (){
var value = fn(test.arg)
assert.equal(value, test.expect)
})
})
})
})
also tried:
describe('example', function () {
getTests().then(function (tests) {
tests.forEach(function (test) {
it('should return ' + test.expect, function (){
var value = fn(test.arg)
assert.equal(value, test.expect)
})
})
})
})
However in this example none of the tests run because mocha doesn't recognize the describe statement because it's within a promise.
before
/ beforeEach
won't do anything to help with a test in the format anyway unless the was a beforeTest
hook that would supply mocha with the knowledge that there's an async operation that needs to be run before the entire test.
I would move the async logic within the
it
call. Getting too fancy with unit tests is a code smell and likely to just irritate other developers when they not only have to debug and fix failing tests but have to debug and fix tests that aren't even defined and running because the fancy setup code has bugs. Try hard not to go there.As an alternative to Daniel Perez's method you can also use the command line switch
--delay
and start the tests on the firstrun()
call. By delaying therun()
asynchronously you can registerdescribe
s andit
s asynchronously beforehand. Note, though, that you can only callrun()
once, i.e. only in one test file. Thus I've created an async test runner in./test/
and each async test in./testAsync/
:and
I am not sure if there is any easy way to do this, but you could try to run Mocha programatically.
Here is a little dirty version of what this could look like, just to show the idea.
data.js
test-launcher.js
test/index.js
You can then run you rests by running
test-launcher.js
.I would use the async/await with delay option as below: