开玩笑的each` each`导致一次被称为一次,但被称为多次称为'与' getByTestID一起使用时出错

发布于 2025-02-13 07:16:21 字数 990 浏览 0 评论 0原文

我有一个组件,其中一些零件是根据window对象上的某些配置条件渲染的。这一切都可以,我可以手动确认这一点。

我有这样的测试设置,但是我已经简化了它:

it('renders both by default', () => { // PASS
  const Comp = getComponent();
  render(<Comp />);
  expect(screen.getByTestId('one')).toBeInTheDocument();
  expect(screen.getByTestId('two')).toBeInTheDocument();
})
it.each([
  { testId: 'one', otherTestId: 'two'},
  { testId: 'two', otherTestId: 'one' },
])('renders $testId, not $otherTestId', (testId, otherTestId) => { // FAIL
  delete window.config[otherTestId]; // this works
  const Comp = getComponent();
  render(<Comp />);
  expect(screen.getByTestId(testId)).toBeInTheDocument();
  expect(screen.getByTestId(otherTestId)).not.toBeInTheDocument();
})

但是我遇到了这个错误:

Expected done to be called once, but it was called multiples times. Reason 'two'.

这不是我以前见过的。我在这里运行的测试都不是异步。该组件不是异步。我没有在此附近使用任何地方。

发生了什么事?

I have a component with some parts that are conditionally rendered based on some config on the window object. This all works, I can confirm this manually.

I have this sort of test setup, but I have simplified it somewhat:

it('renders both by default', () => { // PASS
  const Comp = getComponent();
  render(<Comp />);
  expect(screen.getByTestId('one')).toBeInTheDocument();
  expect(screen.getByTestId('two')).toBeInTheDocument();
})
it.each([
  { testId: 'one', otherTestId: 'two'},
  { testId: 'two', otherTestId: 'one' },
])('renders $testId, not $otherTestId', (testId, otherTestId) => { // FAIL
  delete window.config[otherTestId]; // this works
  const Comp = getComponent();
  render(<Comp />);
  expect(screen.getByTestId(testId)).toBeInTheDocument();
  expect(screen.getByTestId(otherTestId)).not.toBeInTheDocument();
})

But I am getting this error:

Expected done to be called once, but it was called multiples times. Reason 'two'.

Which is not something I've ever seen before. None of my tests that are running here are async. The component isn't async. I'm not using done anywhere near this.

What's happening?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自演自醉 2025-02-20 07:16:21

您需要破坏测试变量

Jest期望testID是包含所有测试变量的对象,而etherTestId是功能完成。

我不确定为什么它认为它被称为多次,但是提出第一个参数:

{ testId, otherTestId }

围绕此操作,并正确匹配文档。


另外,请按照以下内容答案用本机替换Jest的循环,这在许多方面都是更好的方法。

You need to destructure your test variables

Jest is expecting testId to be an object containing all your test variables, and otherTestId to be the function done.

I'm not sure why it thinks it's called multiple times, but making the first argument:

{ testId, otherTestId }

Works around this, and matches the documentation correctly.


Alternatively, follow this answer for replacing jest's for loop with the native one, which is a better approach in many ways.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文