【发布时间】:2017-11-28 04:40:28
【问题描述】:
我正在为 React 应用程序编写集成测试,即一起测试多个组件的测试,并且我想模拟对外部服务的任何调用。
问题是测试似乎在异步回调执行之前执行,导致我的测试失败。
这有什么问题吗?我可以以某种方式等待调用异步代码完成吗?
这里有一些糟糕的伪代码来说明我的观点。
我想测试一下,当我挂载 Parent 时,它的 Child 组件会渲染从外部服务返回的内容,我将对其进行模拟。
class Parent extends component
{
render ()
{
<div>
<Child />
</div>
}
}
class Child extends component
{
DoStuff()
{
aThingThatReturnsAPromise().then((result) => {
Store.Result = result
})
}
render()
{
DoStuff()
return(<div>{Store.Result}</div>)
}
}
function aThingThatReturnsAPromise()
{
return new Promise(resolve =>{
eternalService.doSomething(function callback(result) {
resolve(result)
}
}
}
当我在测试中执行此操作时,它失败了,因为它在回调被触发之前被执行。
jest.mock('eternalService', () => {
return jest.fn(() => {
return { doSomething: jest.fn((cb) => cb('fakeReturnValue');
});
});
describe('When rendering Parent', () => {
var parent;
beforeAll(() => {
parent = mount(<Parent />)
});
it('should display Child with response of the service', () => {
expect(parent.html()).toMatch('fakeReturnValue')
});
});
我该如何测试呢?我知道 Angular 使用 zonejs 解决了这个问题,React 中是否有等效的方法?
【问题讨论】:
-
@Gegenwind jestjs.io/docs/en/asynchronous.html 不相关吗?这只是
expect.assertions()的事情。我不会在答案中转储文档中的示例...
标签: reactjs mocking jestjs enzyme