Reactjs 使用jest/Ezyme测试调用setState的异步componentDidMount
我的Reactjs 使用jest/Ezyme测试调用setState的异步componentDidMount,reactjs,jestjs,enzyme,Reactjs,Jestjs,Enzyme,我的异步组件didmount中有以下代码: async componentDidMount() { try { let responseText = await API.Licensing() this.setState({ html: responseText }) } catch (e) { this.setState({ html: 'Error Fetching Licensing Info' }) } } 我对如
异步组件didmount
中有以下代码:
async componentDidMount() {
try {
let responseText = await API.Licensing()
this.setState({ html: responseText })
} catch (e) {
this.setState({ html: 'Error Fetching Licensing Info' })
}
}
我对如何在这里测试setstate感到困惑,因为来自internet的大多数示例都使用promissionthen/catch,而这个示例使用try/catch async/await
测试看起来怎么样?它可能看起来像这样
test('Sets html to state', async () => {
// Mock your api here...
// using enzyme
const component = await shallow(<YourComponent/>)
// Waiting for all the promises in `componentDidMount` to resolve
// max `i` may vary, it depends on the number of 'awaits' in your code
for (let i = 0; i < 9; i++) {
await component.update()
}
expect(component.state('html')).toBe('someHtml')
})
test('set html to state',async()=>{
//在这里模拟你的api。。。
//使用酶
const component=await shallow()
//等待“componentDidMount”中的所有承诺得到解决
//max`i`可能会有所不同,这取决于代码中的“等待”数量
for(设i=0;i<9;i++){
等待组件。更新()
}
expect(component.state('html')).toBe('someHtml'))
})
它可能看起来像这样
test('Sets html to state', async () => {
// Mock your api here...
// using enzyme
const component = await shallow(<YourComponent/>)
// Waiting for all the promises in `componentDidMount` to resolve
// max `i` may vary, it depends on the number of 'awaits' in your code
for (let i = 0; i < 9; i++) {
await component.update()
}
expect(component.state('html')).toBe('someHtml')
})
test('set html to state',async()=>{
//在这里模拟你的api。。。
//使用酶
const component=await shallow()
//等待“componentDidMount”中的所有承诺得到解决
//max`i`可能会有所不同,这取决于代码中的“等待”数量
for(设i=0;i<9;i++){
等待组件。更新()
}
expect(component.state('html')).toBe('someHtml'))
})
另一件事是,您可能不需要这里的done参数,因为api响应是存根的,但比sorry更安全!需要检查这一个了:)(我必须设置一个项目来检查这个,因为我很好奇…)
PS:对于多个承诺,您只需要根据需要修改MockResolvedValue一次api响应。请点击此处:
说明:您模拟您的API响应并浅显您的组件。然后,您需要在setImmediate函数中执行所有检查。老实说,把这个函数放在哪里并不重要。如果你好奇,试着把它放在试块的顶部。它总是在所有承诺和回调解决后的最后执行。或者,您可以将process.nextTick或setTimeout与0 time参数一起使用。您可以在nodeJS文档中找到更多信息:
基本上,您可以利用JS事件循环的不同队列、计时器回调等
另一件事是,您可能不需要这里的done参数,因为api响应是存根的,但比sorry更安全!需要检查这一个了:)(我必须设置一个项目来检查这个,因为我很好奇…)
PS:对于多个承诺,您只需要根据需要修改MockResolvedValue一次api响应。请点击此处:
说明:您模拟您的API响应并浅显您的组件。然后,您需要在setImmediate函数中执行所有检查。老实说,把这个函数放在哪里并不重要。如果你好奇,试着把它放在试块的顶部。它总是在所有承诺和回调解决后的最后执行。或者,您可以将process.nextTick或setTimeout与0 time参数一起使用。您可以在nodeJS文档中找到更多信息:
基本上,您可以利用JS事件循环的不同队列、计时器回调等如果您解释代码,您的答案会更好。:)@markus是否更好如果您解释代码,您的答案会更好。:)更好吗@Markus
import API from './API';
jest.mock("API");
... API.Licensing.mockResolvedValueOnce(responseText);