【发布时间】:2021-10-03 18:27:52
【问题描述】:
我有一个文件要测试,如下所示:
function handleButtonClick() {
getData().then(() => {
// Do something here
}).catch((err) => {
// Handler error here
}).finally(() => {
// Set color state to yellow
});
}
我的测试看起来像这样
let getDataResolve;
const getData = jest.fn();
getData.mockReturnValue(
new Promise(res => {
getDataResolve = res;
})
);
it('should change color to yellow on button click', async () => {
const myButton = ...do something to grab the button here;
fireEvent.click(myButton);
await getDataResolve({});
expect(// here expect color is set to yellow);
});
但是我的测试失败了,因为通过在我的测试中调用await getDataResolve({}),我只能触发then 块运行,而expect line 在finally block 之前运行。但我想在运行finally 块之后运行expect。无论如何我可以做到这一点吗?我真的不明白finally 块是如何以及何时触发的。非常感谢您的帮助!
【问题讨论】:
-
嗨,Bravo,感谢您的评论,那么如果我想在我的测试中使用
expect行,您有什么建议?更改代码以使测试工作显然不是一个好习惯。 -
组件中的某处会有一个按钮,并且有一个 onClick 处理程序,即 handleButtonClick。在测试中,我能够抓住那个按钮并模拟点击它。我不知道这是否能消除你的困惑。
-
告诉你什么,因为我似乎很困惑,所以我将删除我的 cmets,也许更了解的人可以提供帮助
-
尝试将
expect包裹在waitFor中:await waitFor(() => expect(...));
标签: javascript promise jestjs es6-promise react-testing-library