标签: jest-mock-axios

UnhandledPromiseRejectionWarning: TypeError: 在测试环境被拆除后捕获错误

在运行测试时出错的发布请求图像中出现测试失败时获取错误

使用 Reactjs 框架版本 16

用于 api 请求的 axios-hooks

用于测试的反应测试库

UnhandledPromiseRejectionWarning: TypeError: 在测试环境被拆除后捕获错误

无法读取 null 的属性“nodeType”(节点:171) UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个错误要么是因为在没有 catch 块的情况下抛出了异步函数,要么是因为拒绝了一个没有用 .catch() 处理过的承诺。(拒绝编号:4)

测试代码

test('If user enters an invalid email or password', async () => {
  const { getByText, getByLabelText, getByTestId } = render(
    <Provider store={mockStore}>
      <Login />
    </Provider>
  )
  fireEvent.change(getByLabelText('Email'), {
    target: { value: 'test@emailing.com' }
  })
  fireEvent.change(getByLabelText('Password'), {
    target: { value: 'password' }
  })

  getByText('Sign in').click()
  await waitForDomChange()
  await act(async () => {
    try {
      await MockAxios.mockError({ …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-testing-library jest-mock-axios

8
推荐指数
0
解决办法
7344
查看次数

避免有条件地调用“expect”:玩笑测试错误

我正在尝试在响应被拒绝时测试具有负面情况的异步代码。

根据文档,我们可以在尝试实现模拟拒绝时使用 try、catch 和 async wait https://jestjs.io/docs/tutorial-async

// Or using async/await.
it('tests error with async/await', async () => {
  expect.assertions(1);
  try {
    await user.getUserName(1);
  } catch (e) {
    expect(e).toEqual({
      error: 'User with 1 not found.',
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

我尝试通过实现模拟拒绝值来执行相同的操作。但是,我收到以下错误:Avoid calling 'expect' conditionally。我还添加了expect.assertions(),但错误仍然存​​在。我知道可以启用 eslintjest/no-conditional-expect,但这是一个我不想遵循的坏习惯。

我的实现

it("Should reject with with message, User already exists with same email", async () => {
   expect.assertions(1);
    try {
        await signupService(userSignupData);
    } catch (e) {
        expect(e).toContain("User already exists");
    }
});
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏。谢谢!

PS我看到了类似的问题,但没有解决。

jestjs ts-jest jest-mock-axios react-typescript

3
推荐指数
1
解决办法
7115
查看次数