首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当它应该测试的时候,Jest不会失败

当它应该测试的时候,Jest不会失败
EN

Stack Overflow用户
提问于 2021-04-15 07:25:24
回答 1查看 472关注 0票数 1

我从jest-fetch-模拟npm包示例中获取了确切的代码示例,我不能让它失败。有人能告诉我我做错了什么吗?

这是我的密码:

代码语言:javascript
复制
require('jest-fetch-mock').enableMocks();

const APIRequest = (who) => {
  if (who === 'google') {
    return fetch('https://google.com').then((res) => res.json());
  } else {
    return 'no argument provided';
  }
};

describe('testing api', () => {
  beforeEach(() => {
    fetch.resetMocks();
  });

  it('calls google and returns data to me', () => {
    fetch.mockResponseOnce(JSON.stringify({ data: '12345' }));

    //assert on the response
    APIRequest('google').then((res) => {
      expect(res.data).toEqual('not 12345');
    });
  });
});

即使,很明显,我对fetch的模拟响应与我预期的结果不匹配,但jest仍然说测试通过了,为什么?它告诉我,在“测试通过”部分上,它收到了比预期更多的东西,但是测试仍然显示“通过”,为什么?我怎样才能让它在这种情况下失败,在这种情况下它是如何被期望的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-15 07:32:10

对您的问题有两种可能的解决方案:

  1. 使用expect.assertions来开玩笑,验证是否所有断言都被断言为,并返回一个expect.assertions

代码语言:javascript
复制
  it('calls google and returns data to me', () => {
    fetch.mockResponseOnce(JSON.stringify({ data: '12345' }));

    expect.assertions(1);

    //assert on the response
    return APIRequest('google').then((res) => {
      expect(res.data).toEqual('not 12345');
    });
  });
});

如果您返回承诺,jest将知道代码运行异步。

  1. 使用异步/等待

使用async/await语法:

代码语言:javascript
复制
it('calls google and returns data to me', async () => {
    fetch.mockResponseOnce(JSON.stringify({ data: '12345' }));

    expect.assertions(1);

    //assert on the response
    const result = await APIRequest('google')
    expect(result).toEqual('not 12345');
  });
});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67104029

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档