【问题标题】:How do I get rid of this warning in my React Native test?如何在我的 React Native 测试中摆脱这个警告?
【发布时间】:2020-10-11 23:18:54
【问题描述】:

React 告诉我使用 act 测试助手,但我收到以下警告:

Cannot log after tests are done. Did you forget to wait for something async in your test? Attempted to log "Warning: You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);".

这是我的测试:

it('navigates to MainScreen on submit', () => {
    const props = createMockNav()
    const setUser = jest.fn()
    const result = renderer.create(
      <MockedProvider mocks={[]}>
        <UserContext.Provider value={{ setUser: setUser }}>
          <LoginScreen {...props} />
        </UserContext.Provider>
      </MockedProvider>
    )
    const testInstance = result.root
    const button = testInstance.findByType(Button)
    expect(button.props.title).toBe('Login!')
    act(async () => {
      button.props.onPress()
      await wait(0);
      expect(props.navigation.navigate).toHaveBeenCalledTimes(1)
    })
  })

我尝试在 act 调用内部或外部移动东西,但我要么破坏它,要么仍然收到警告。任何帮助表示赞赏。

【问题讨论】:

    标签: reactjs react-native jestjs


    【解决方案1】:

    如果可行的话,或许你可以试试这样……

    it('navigates to MainScreen on submit', async() => {            //Here  
      const props = createMockNav()
      const setUser = jest.fn()
      const result = renderer.create(
        <MockedProvider mocks={[]}>
          <UserContext.Provider value={{ setUser: setUser }}>
            <LoginScreen {...props} />
          </UserContext.Provider>
        </MockedProvider>
      )
      const testInstance = result.root
      const button = testInstance.findByType(Button)
      expect(button.props.title).toBe('Login!')
      await act( async () => {                                      //And here
        button.props.onPress()
        await wait(0);
        expect(props.navigation.navigate).toHaveBeenCalledTimes(1)
      })
    })
    

    【讨论】:

    • 啊好主意,将async 放在测试函数上。但可惜我得到:ReferenceError:未定义等待> 77 |等待动作(异步()=> {
    • 哦,故障中问题点的 ^ 在那个异步下。我尝试将“等待等待(0)”取出,但当然这不起作用。感谢您的尝试!
    猜你喜欢
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多