【发布时间】:2021-09-20 16:47:00
【问题描述】:
我有一个带有以下 Player 组件的 React Native 应用程序,它无限地调用带有 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)
}
}
【问题讨论】:
标签: react-native react-native-testing-library