我有一个带有以下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()
andjest.runOnlyPendingTimers()
时,waitFor
函数出错并出现timeout
错误。如何监视 setTimeout?这是我的组件的总体思路:
class Player extends Component {
componentDidMount(){
this.play()
}
play() {
//does some things
setTimeout(play, 1000)
}
}