我有一个带有以下Player组件的React Native应用程序,它可以无限地调用带有setTimeout的play()函数。我和jest一起使用react-native-testing-library进行渲染/测试。
我正在尝试测试这个setTimeout函数。具体地说,我想要监视这个函数,这样我就可以预期在给定的一组秒数之后,setTimeout会被调用任意次。例如,在3秒后,该函数应该已经被调用了3次。然而,我在测试时遇到了问题。我现在的测试是这样的:
fit('displays the content', async () => {
//jest.useFakeTimers();
const { debug, toJSON, getByText, getByTestId } = render(
<Player token={'test-token'} saveToken={saveTokenMock} />
);
//jest.runOnlyPendingTimers();
const data = {"device":{"id":58,"updated_at":"2021-07-05T01:39:53.588Z","events":[{"my data here"}]}]}};
mock.onPost('https://www.mydomain.io/api/v1/devices/events').reply(200, data);
await waitFor(() => {
expect(getByTestId('imageAsset')).toBeTruthy();
expect(toJSON()).toMatchSnapshot()
});
})当我添加jest.useFakeTimers()和jest.runOnlyPendingTimers()时,waitFor函数出现错误,并出现timeout错误。我如何监视setTimeout?下面是我的组件的一般概念:
class Player extends Component {
componentDidMount(){
this.play()
}
play() {
//does some things
setTimeout(play, 1000)
}
}发布于 2021-07-19 04:22:12
您可以使用jest提供的advanceTimersByTime将时间提前。要检查函数调用的数量,请使用toHaveBeenCalledTimes。
Jest文档中提供的示例与您的组件非常相似。
https://stackoverflow.com/questions/68331767
复制相似问题