When using Jest to test async code that utilizes callbacks you can put in a done parameter that you then call inside the test. This allows the test to know to wait until the done() function is called before it finishes the test. For example this code will not finish until the callback containing the done() function is run.
test('the data is peanut butter', done => {
function callback(data) {
expect(data).toBe('peanut butter');
done();
}
fetchData(callback);
});
My question is, how does Jest actually know when it needs to wait for that done() call? As the only other place it exists is in the parameter of the function the test runs, does Jest have a way of checking to see what parameters are in that function? If so how does it do this?
A function has a .length
property that returns the number of arguments that are declared for it:
function test0() {}
function test1(arg0) {}
function test2(arg0, arg1) {}
console.log( test0.length ); // 0
console.log( test1.length ); // 1
console.log( test2.length ); // 2
That's how Jest knows that your test handler expects a done
callback, and it will assume the test is asynchronous.
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