开玩笑的each` each`导致一次被称为一次,但被称为多次称为'与' getByTestID一起使用时出错
我有一个组件,其中一些零件是根据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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要破坏测试变量
Jest期望
testID
是包含所有测试变量的对象,而etherTestId
是功能完成。我不确定为什么它认为它被称为多次,但是提出第一个参数:
围绕此操作,并正确匹配文档。
另外,请按照以下内容答案用本机替换Jest的循环,这在许多方面都是更好的方法。
You need to destructure your test variables
Jest is expecting
testId
to be an object containing all your test variables, andotherTestId
to be the functiondone
.I'm not sure why it thinks it's called multiple times, but making the first argument:
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.