Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Jest's callback testing actually work

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?

like image 839
Kee Avatar asked Jul 17 '17 16:07

Kee


1 Answers

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.

like image 200
robertklep Avatar answered Nov 03 '22 02:11

robertklep