简体   繁体   中英

Mocha tests with async initialization code

I am writing tests for a REST client library which has to "login" against the service using the OAuth exchange. In order to prevent logging in for every endpoint I am going to test I'd like to write some sort of "test setup" but I am not sure how I am supposed to do this.

My test project structure:

  • test
    • endpoint-category1.spec.ts
    • endpoint-category2.spec.ts

If I had only one "endpoint category" I had something like this:

describe('Endpoint category 1', () => {
  let api: Client = null;

  before(() => {
    api = new Client(credentials);
  });

  it('should successfully login using the test credentials', async () => {
    await api.login();
  });

  it('should return xyz\'s profile', async () => {
    const r: Lookup = await api.lookup('xyz');
    expect(r).to.be.an('object');
  });
});

My Question:

Since the login() method is the first test there, it would work and the client instance is available for all the following tests as well. However, how can I do some sort of setup where I make the "logged in api instance" available to my other test files?

Common code should be moved to beforeEach :

  beforeEach(async () => {
    await api.login();
  });

At this point should successfully login using the test credentials doesn't make much sense because it doesn't assert anything.

describe('Endpoint category 1', () => {
  let api: Client = null;

  beforeEach(() => {
    api = new Client(credentials);
  });

  afterEach(() => {
    // You should make every single test to be ran in a clean environment.
    // So do some jobs here, to clean all data created by previous tests.
  });

  it('should successfully login using the test credentials', async () => {
    const ret = await api.login();
    // Do some assert for `ret`.
  });

  context('the other tests', () => {
    beforeEach(() => api.login());
    it('should return xyz\'s profile', async () => {
      const r: Lookup = await api.lookup('xyz');
      expect(r).to.be.an('object');
    });
  });
});

Have you had a look at https://mochajs.org/#asynchronous-code ?

You can put in a done-parameter in your test functions and you will get a callback with this you have to call.

done() or done(error/exception)

This done would be also available in before and after.

When calling done() mocha knows your async-code has finished.

Ah. And if you want to test for login, you shouldn't provide this connection to other tests, because there is no guarantee of test order in default configuration.

Just test for login and logout afterwards.

If you need more tests with "login-session", describe a new one with befores.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM