【问题标题】:React user testing with Jest executes test before BeforeEach method finishes使用 Jest 反应用户测试在 BeforeEach 方法完成之前执行测试
【发布时间】:2021-04-19 19:52:10
【问题描述】:

我目前正在尝试使用 React 测试库和 Jest 测试一个 React 应用程序。这是我的代码的 sn-p:

const renderComponent = async () => {
  component = render(
      <Component
        ... props
      ></Component>
  ).container

  return waitFor(() =>
    expect(
      component.querySelector(#some-element)
    ).toBeInTheDocument(),
  ).then(() => {
      console.log("done with method")
      return "good to go"
  })
}

beforeEach(async () => {
  return renderComponent().then(() => {
    console.log("done")
    return "done with before each"
  })
})

test('should test work', async () => {
  const element = getById(component as HTMLElement, 'element-id')
  userEvent.type(element!, "hello")
  // this test fails
  expect(mockFunction).lastCalledWith("hello")
})

我的问题不是我的测试失败,而是测试套件的执行顺序。在我的控制台中,console.log 消息按以下顺序打印出来:

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        4.123 s

Watch Usage: Press w to show more.  
 console.log
    done with method

  console.log
    done with before each

为什么在 beforeEach 中的逻辑完成之前测试失败了?任何帮助,将不胜感激!谢谢:)

【问题讨论】:

  • 我不知道到底是什么问题,但由于传递给beforeEach 的异步方法,它似乎可能会出现故障。
  • 你认为方法不应该是异步的吗?我只是尝试删除 async 关键字,不幸的是,它没有做任何事情。测试应该在 beforeEach 方法中的承诺解决后运行,如 Jest 文档中所述:“在此文件中的每个测试运行之前运行一个函数。如果函数返回一个承诺,Jest 等待该承诺解决在运行测试之前。”
  • 尽量将您的断言放在test 块中,而不是beforeEach 中。在这种情况下,直接在您的测试中调用await renderComponent()

标签: reactjs jestjs react-testing-library


【解决方案1】:

由于renderComponent 是异步的,运行它立即返回,而不执行函数中的任何代码。

您应该等待它,因此它会阻止 beforeEach 的完成,直到 renderComponent 完成。

beforeEach(async () => {
  await renderComponent().then(() => {
    console.log("done")
    return "done with before each"
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-13
    • 2021-11-15
    • 1970-01-01
    • 2021-09-11
    • 2020-11-02
    • 1970-01-01
    • 2019-06-26
    • 2019-03-22
    相关资源
    最近更新 更多