Search code examples
javascriptreactjsasynchronousasync-awaitnock

Test asynchronous async await JavaScript function


I've written an asynchronous JavaScript function though do not seem to be getting the returned value I expect. Could somebody explain if I'm misunderstanding how async functions work or if it's something not quite right my test?

Below is my test, with a service mocked using Nock.

it('Should call async validation function when button is clicked', () => {
    const request = nock(/.*/)
      .get('/my-service/logincodes/abc123')
      .reply(404);

    const comp = mount(
      <LoginCodeView />
    );
    expect(comp.instance().doesLoginCodeExist('abc123')).to.equal('Your Login code is not recognized.');
 });

And the function under test:

  doesLoginCodeExist = async (loginCode) => {
    if (loginCode.match(loginPattern)) {
      const response = await MyService.getUserByLoginCode(loginCode);

      if (response.code) {
        return {};
      } else if (response.status === 404) {
        return { error: 'Your login code is not recognized.', success: null };
      }
      return { error: 'Service is temporarily unavailable.', success: null };
    }
    return null;
  };

I've logged out which route the code takes and it does appear to be going into the else if branch as expected, however I always get an empty object {} returned, not an object with error and success properties as expected?


Solution

  • An async function always returns a Promise object. I suspect this is what you are calling an empty object.

    As a solution, you might try making your test function async and using await there too. Then you can test the value the promise resolves to.