我有一个React Native应用程序,它包含以下Player
组件,该组件使用setTimeout
无限调用play()
函数。我使用react-native-testing-library
和jest
进行渲染/测试。
我正在尝试测试这个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)
}
}
您可以使用jest提供的advanceTimersByTime来提前时间。要检查函数调用的次数,请使用HaveBeenColledTimes。
Jest文档中提供的示例与您的组件非常相似。