我有一个带有以下 Player
组件的 React Native 应用程序,该组件使用 play()
无限调用 setTimeout
函数。我使用 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)
}
}
答案 0 :(得分:0)
您可以使用 jest 提供的 advanceTimersByTime 来提前时间。 要检查函数调用的数量,请使用 toHaveBeenCalledTimes。
Jest 文档中提供的示例与您的组件非常相似。