Skip to content

How to Debug Mocha Tests

Ijemma Onwuzulike edited this page May 1, 2021 · 2 revisions

This guide will walk through the steps taken while debugging Mocha tests.

  1. If a test is failing, single out that test by using it.only(). This will save you time by only running that single test.

You can do this by adding it.only to any existing test:

- it('should return word information', (done) => {
+ it.only('should return word information', (done) => {
      const keyword = 'bia';
      getWords({ keyword })
        .end((_, res) => {
          done();
        });
    });

Note: You can apply .only() to multiple it and describe blocks.

yarn mocha

Note: Remember to remove .only() before pushing so all the tests can run in GitHub Actions.

  1. Now that you have your single test, the next thing to do is print out the response from the server by printing out res.body.

If an error occurred, you should be able to read it in res.body.

it.only('should return word information', (done) => {
      const keyword = 'bia';
      getWords({ keyword })
        .end((_, res) => {
+         console.log(res.body); // This will print out the response from the server
          expect(res.status).to.equal(200);
          done();
        });
    });

From there, your search throughout the codebase will be more targeted since the error message has described what's going on.

  1. (Optional) Some tests require there to be words already present in the database. For example, tests that use the function getWords() needs words in the database. In this case, you want to also apply describe.only() to the describe block that's responsible for populating the testing database in api-json.js.
- describe('JSON Dictionary', () => {
+ describe.only('JSON Dictionary', () => {
  before(function (done) {
    this.timeout(120000);
    server.clearDatabase();
    populateAPI()
      .end(() => {
        setTimeout(() => done(), 10000);
      });
  });
...
Clone this wiki locally