简体   繁体   English

测试异步异步等待JavaScript函数

[英]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. 我编写了一个异步JavaScript函数,但似乎没有获得我期望的返回值。 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. 以下是我的测试,使用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? 我已经注销了代码所采用的路径,并且看起来似乎是按照预期进入else if,但是我总是返回一个空对象{},而不是具有错误和成功属性的对象如预期的那样?

An async function always returns a Promise object. async函数始终返回Promise对象。 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. 作为解决方案,您可以尝试使您的测试函数asyncawait那里使用await Then you can test the value the promise resolves to. 然后,您可以测试promise解决的值。

Making my test async await solved the issue. 让我的测试异步等待解决了这个问题。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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