我对Jest和一般测试都比较新.我有一个带有输入元素的组件:
import * as React from "react";
export interface inputProps{
placeholder: string;
className: string;
value: string;
onSearch: (depID: string) => void;
}
onSearch(event: any){
event.preventDefault();
//the actual onclick event is in another Component
this.props.onSearch(event.target.value.trim());
}
export class InputBox extends React.Component<inputProps, searchState> {
render() {
return (
<input
onChange={this.onSearch} //need to test this
className={this.props.className}
type="text"
value={this.props.value}
placeholder={this.props.placeholder} />
);
}
}
Run Code Online (Sandbox Code Playgroud)
我想要一个测试来检查输入元素onChange是一个函数,它接受输入元素的value属性作为参数.这是到目前为止我已经走了多远:
//test to see the input element's onchange
//returns a function that takes its value as …Run Code Online (Sandbox Code Playgroud) 我读到 act / waitFor 是等待 DOM 更新。我还读到渲染是同步的。我假设我不需要用 act/waitFor 包装渲染,因为当我单击或测试时 DOM 总是会更新?它是否正确 ?
接下来,我不明白为什么我需要 act / waitFor ? 我不能只是等待吗? 对于测试A,我使用user.click,并且我看到在线示例代码使用await。它似乎在我的笔记本电脑上运行良好。
然而,在测试 B 中,当我看到 fireEvent.click 的一些示例代码时,他们使用了 waitFor。我尝试使用等待,它标记我“等待对这种类型的表达式没有影响”。但“await waitFor()”有效。为什么是这样 ?
首先十分感谢 !
Test A
it('user.click', async () => {
render(
<BrowserRouter>
<Notes />
</BrowserRouter>
);
const checkBox = screen.getByRole('checkbox');
await user.click(checkBox);
const prev = screen.getByRole('button', { name: 'Prev' });
expect(prev).toBeEnabled();
});
Test B
it('fireEvent.click', async () => {
render(
<BrowserRouter>
<Notes />
</BrowserRouter>
);
const checkBox = screen.getByRole('checkbox');
await fireEvent.click(checkBox);
const prev = …Run Code Online (Sandbox Code Playgroud)