mardi 26 novembre 2019

Why is done() not being called inside .then callback? (Mocha/Chai/Node.js)

I may have misunderstood something about async tests using Mocha and Chai or I may have done something wrong. I assume that there's something that prevents done() being called inside the then() callback. Given the test below:

describe('Post', () => {
    it('should return 201 and have valid title, body, and author', (done) => {
        //mock input
        const new_post = {
            "title": "Sample title",
            "body": "This is the sample body. The author writes down something in this part.",
            "author": "User"
        }

        chai.request(app).post('/addPost').send(new_post).then((res) => {
            expect(res).to.have.status(201);
            expect(res.body.message).to.be.equal("Post created");

            expect(res.body.post.title).to.exist;
            expect(res.body.post.body).to.exist;
            expect(res.body.post.author).to.exist;
            done();
        })
        .catch(err=>{
            done(err);
        });
    });
});

I had given an invalid mock input (e.g. blank title/body/author) and the test above "correctly" shows an error and fails as I expected. Yet when given complete and valid mock input (as shown above), the test still fails and shows an Error Timeout cmd error output

//cmd output
  1) Post
       should return 201 and have valid title, body, and author:
     Error: Timeout of 5000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
      at listOnTimeout (internal/timers.js:531:17)
      at processTimers (internal/timers.js:475:7)


npm ERR! Test failed.  See above for more details.

I even tried calling done() after calling async function (it()) but this just always results into the test passing no matter what the input may be.

Any help or enlightenment would be appreciated as I'm just self-learning testing using Mocha and Chai.

Aucun commentaire:

Enregistrer un commentaire