【问题标题】:Test setTimeout with React Native Testing Library and Jest使用 React Native 测试库和 Jest 测试 setTimeout
【发布时间】: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


    【解决方案1】:

    您可以使用 jest 提供的advanceTimersByTime 来提高时间。 要检查函数调用的数量,请使用toHaveBeenCalledTimes。

    Jest 文档中提供的示例与您的组件非常相似。

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 2022-06-11
      • 2020-03-24
      • 1970-01-01
      • 2020-06-14
      • 2018-03-24
      • 2018-01-29
      • 2016-07-22
      • 2019-04-22
      相关资源
      最近更新 更多