1

I am using Mocha and Chai to test my async js code.

I need to wait for previous tests to complete before starting the next test. ex] create account -> update account -> delete account

Here is a simplified version of the test code:

  describe('Account Tests', function() {
    this.timeout(30000);

    // I want to run this 1st
    it('should create account', async function() {
      let account = await api.acount.create();
      expect(account).not.to.be.null;
    })

    // I want to run this 2nd
    it('should update account', async function() {
      let accountUpdate = await api.account.update();
      expect(accountUpdate.status).to.equal(204);
    })

    // I want to run this last
    it('should delete account', async function() {
      let result = await api.account.remove();
      expect(result).to.be.true;
    })
  })

Since I am using promises with async & await, the promise is inherently returned to 'it'

The problem I am encountering is sometimes the account is created then deleted before the update test can run. So, the update test fails while the create & delete tests pass. Sometimes the delete test tries to run before the create test is finished and so fails. I know I can add a sleep in between these tests, but I don't want to use a 'hack' when there is a real solution.

I'm new using Mocha and Chai, and I must be missing something here, but shouldn't the promise make the creating an account test wait until that is finished before running the update test?

isherwood
  • 58,414
  • 16
  • 114
  • 157
9thWave
  • 31
  • 8
  • 1
    Tests should not be dependent on each other. Use mocks or stubs rather than such dependencies. – isherwood Jun 30 '21 at 21:37
  • 2
    https://stackoverflow.com/questions/9736429/how-can-i-execute-async-mocha-tests-nodejs-in-order seems to be direct duplicate. But there's [more](https://stackoverflow.com/questions/25137899/running-mocha-tests-synchronously); have you checked those? – raina77ow Jun 30 '21 at 21:39
  • Thanks, I agree with this and will be looking to implement that. In the meantime as a temporary fix and for my own edification, do you know why test 2 is not waiting for the return of the promise from test 1? – 9thWave Jun 30 '21 at 21:43
  • Thanks, I don't think I came across those yet while looking to solve this problem - I will take a look now. – 9thWave Jun 30 '21 at 21:46
  • Does this answer your question? [How can I execute async Mocha tests (NodeJS) in order?](https://stackoverflow.com/questions/9736429/how-can-i-execute-async-mocha-tests-nodejs-in-order) – amda Jul 01 '21 at 11:26

0 Answers0