0

Code-1:

describe("testing server functionalities", () => {
    
    // test case
    it("server handles a function", () => {
        request('some link', (error, response, body) => {
            var expected = "1410";
            expect(expected).to.be.equal(body);
        })
    })

});

Code-2:

describe("testing server functionalities", () => {
    
    // test case
    it("server handles a function", (done) => {
        request('some link', (error, response, body) => {
            var expected = "1410";
            expect(expected).to.be.equal(body);
            done();
        })
    })

});

So here in Code-1, we have the problem that the test exits before checking whether the value meets the expected value because the request call is asynchornous.

To handle this problem, I found a way where the introduced argument done as in the Code-2 makes the test function wait for the done() function to get called which finally makes the test function work properly.

But I am not sure how the Code-2 works and why does the test function wait for the done.

Can someone please help me with this?

Sai Sreenivas
  • 1,690
  • 1
  • 7
  • 16
  • What do you mean _why_ does it wait for done? Because that's the _whole point_ of it, so you can inform the test runner when you consider the test complete. But I'd encourage the use of one of the other options: https://jestjs.io/docs/asynchronous – jonrsharpe Aug 25 '21 at 21:38
  • @jonrsharpe so you are saying it's to do with the internal logic of Jest framework and nothing to do with the concept of callback right? – Sai Sreenivas Aug 26 '21 at 04:17
  • 1
    I've no idea what distinction you're trying to draw there. It's the internal logic of the framework, implemented using a callback. – jonrsharpe Aug 26 '21 at 06:43

1 Answers1

0

Here you can see how we could know which arguments does function expects.

And this is the simplest one.

Also it is possible to get this parameters by parsing JS-file to Abstract Syntactic Tree(AST).

And then it is easliy possible to create different logic.

Let's imagine how it could look (abstractly):

// Some testing framework code
const shouldWaitUntilDone = testcase.hasDoneCallback();

if (shouldWaitUntilDone) {
  // Callback will run when done() is called
  testcase.run(() => { testcase.runMatchers(); }) 
} else {
  testcase.run().runMatchers();
}
capchuck
  • 461
  • 2
  • 8