The Javascript Jest testing framework documentation says that I need to add done() in my callback to test an asynchronous function, as otherwise the function will return after the test completes and so the test will fail. I have Jest added to my package.json, and the following two files:
src.js:
function fetchData(cb) {
setTimeout(cb, 2000, 'peanut butter')
}
module.exports = fetchData
src.test.js:
const fetchData = require('./src')
test('the data is peanut butter', () => {
function callback(data) {
expect(data).toBe('peanut butter')
// no done() method!
}
fetchData(callback);
})
I get passing tests with the above code, but I think I should get a failing test since I don't have done() in my test file. Is my fetchData() method not asynchronous?
EDIT: Following Nicholas' answer, I changed the code to this:
src.js:
function fetchData(cb) {
setTimeout(cb, 2000, 'peanut')
}
module.exports = fetchData
src.test.js:
const fetchData = require('./src')
test('the data is peanut butter', () => {
function callback(data) {
expect(data).toBe('peanut butter')
done()
}
fetchData(callback);
})
The test runner should evaluate the expectation/assertion per the Jest documentation and fail (peanut being passed, peanut butter expected), but still shows a passing test.
Also, the Jest documentation says:
If done() is never called, the test will fail, which is what you want to happen
The test passes both with and without the done() method in the callback, and both with and without a correct (peanut butter) argument passed to the callback (i.e. all four variants pass).