5

i want to write a test for test createUser .

i write this code :

const User = require("../src/Entite/User");

describe("Create User", () => {
  it(" Save and Create User ", (done) => {
    const addUser = new User({
      name: "Kianoush",
      family: "Dortaj",
    });
    addUser
      .save()
      .then(() => {
        assert(!addUser.isNew);
        done();
      });
  });
});

when i run the test use was created in database but it show me this error and test fail :

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (F:\Projects\Nodejs\MongooDB\test\create-user_test.js) at listOnTimeout (internal/timers.js:549:17) at processTimers (internal/timers.js:492:7)

whats the problem ? how can i solve that ??

kianoush dortaj
  • 411
  • 7
  • 24
  • Does this answer your question? [In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded](https://stackoverflow.com/questions/16607039/in-mocha-testing-while-calling-asynchronous-function-how-to-avoid-the-timeout-er) – Dez Jul 02 '20 at 18:31

1 Answers1

2

Here a few solutions can be checked.

"scripts": {
          "test": "mocha --timeout 10000"  <= increase this from 1000 to 10000
           },

#### OR ###

it("Test Post Request", function(done) {
     this.timeout(10000);  //add timeout.
});

Test-specific timeouts may also be applied, or the use of this.timeout(0) to disable timeouts all together:

it('should take less than 500ms', function(done){
  this.timeout(500);
  setTimeout(done, 300);
});

If both do not work. Try this

const delay = require('delay')

describe('Test', function() {
    it('should resolve', async function() {
      await delay(1000)
    })
})

Somehow the presence of the done argument in the async function breaks the test, even if it's not used, and even if done() is called at the end of the test.

xMayank
  • 1,875
  • 2
  • 5
  • 19
  • 5
    Worth noting that you need to use the function() form for the anonymous predicate for this to work. The fat arrow form "async () => {" specifically runs in the enclosing context therefore has no "this" object. You will probably see something like "TypeError: this.timeout is not a function" if you've made this mistake. – Curt Eckhart Feb 28 '21 at 00:37