gpt4 book ai didi

javascript - 如何使用 spyOn 测试异步函数?

转载 作者:行者123 更新时间:2023-11-29 22:55:54 25 4
gpt4 key购买 nike

我正在尝试在 React Native 应用程序中测试异步函数。

class myClass extends React.Component {

...

closeModal = async () => {

if (someCondition) {
await myFunction1();
} else {
await myFunction2();
}

this.props.navigation.state.params.onGoBack();
this.props.navigation.navigate('Main');
};

...

}

这是我的测试:

const navigation = {
navigate: jest.fn(),
state: { params: { onGoBack: jest.fn() } },
};

const renderComponent = overrides => {
props = {
navigation,
...overrides,
};

return shallow(< myClass.wrappedComponent {...props} />);
};


describe('When the user presses the close icon', () => {
it('should close the modal', () => {
const wrapper = renderComponent();
const instance = wrapper.instance();
const spyCloseModal = jest.spyOn(instance, 'closeModal');
instance().forceUpdate();
component
.find({ testID: 'close-icon' })
.props()
.onPress();
expect(spyCloseModal).toHaveBeenCalled(); // this is passed
expect(navigation.navigate).toHaveBeenCalled(); // this is not passed
});
});

看起来它卡在等待调用上了。如果我删除 await 调用,它就会通过。有人在另一篇文章中提到在 spyOn 之后使用 .and.callThrough 但它给了我这个错误

Cannot read property 'callThrough' of undefined

最佳答案

解决方案之一是让您的测试async 并运行await (anything) 将您的测试拆分为多个微任务:

it('should close the modal', async () => {
const wrapper = renderComponent();
component
.find({ testID: 'close-icon' })
.props()
.onPress();
await Promise.resolve();
expect(navigation.state.params.onGoBack).toHaveBeenCalled();
expect(navigation.navigate).toHaveBeenCalledWith("Main");
});

我相信您在实例方法上既不需要 .forceUpdate 也不需要 .spyOn。一旦导航正确发生,调用它的内部方法并不重要

关于微任务与宏任务的更多信息:https://abc.danch.me/microtasks-macrotasks-more-on-the-event-loop-881557d7af6f

替代方法是使用 macrotask(setTimeout(...., 0))

it('should close the modal', (done) => {
const wrapper = renderComponent();
component
.find({ testID: 'close-icon' })
.props()
.onPress();
setTimeout(() => {
expect(navigation.state.params.onGoBack).toHaveBeenCalled();
expect(navigation.navigate).toHaveBeenCalledWith("Main");
done();
});
}

关于javascript - 如何使用 spyOn 测试异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56654870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com