【问题标题】:Test React component with async function with mockResolvedValue - the promise is not resolved使用带有 mockResolvedValue 的异步函数测试 React 组件 - 承诺未解决
【发布时间】:2021-01-02 04:58:26
【问题描述】:

我有一个获取异步函数并运行它的组件。

代码示例:

const Foo = ({func}) => {
  const [val, setVal] = useState(null);
  useEffect(()=> {
        async function myAsyncFunf() {
          const newVar = await func();
          setVal(newVar)
        };
        myAsyncFunf();
      },[]);
  return <div>{val}</div>
}
it('test',async()=>{
  const asyncMock = jest.fn().mockResolvedValue(43);
  const props = {func: asyncMock}
  const {getByText} = render(<Foo {...props}/>);
  await wait(() => expect(asyncMock).toHaveBeenCalledTimes(1));
  getByText('43');

});

测试失败并显示此消息:

控制台错误 警告:测试中对 Foo 的更新未包含在 act(...) 中。

When testing, code that causes React state updates should be wrapped into act(...):

act(() => {
  /* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser. Learn more at 

【问题讨论】:

    标签: reactjs promise jestjs es6-promise react-testing-library


    【解决方案1】:

    在你的组件中,func其实和props有关,你只是把它命名为“func”

    您需要对其进行解构才能访问 func,或显式访问对象的属性。

    选项 1 - 解构。注意花括号“{func}”

    const Foo = ({func}) => {
      const [val, setVal] = useState(null);
      useEffect(()=> {
            async function myAsyncFunf() {
              const newVar = await func();
              setVal(newVar)
            };
            myAsyncFunf();
          },[]);
      return <div>{val}</div>
    }
    

    选项2 - 访问“props”的属性“func”

    const Foo = (props) => {
      const [val, setVal] = useState(null);
      useEffect(()=> {
            async function myAsyncFunf() {
              const newVar = await props.func();
              setVal(newVar)
            };
            myAsyncFunf();
          },[]);
      return <div>{val}</div>
    }
    

    【讨论】:

    • 谢谢。现在我收到一条不同的错误消息。我应该用 act 包装什么?
    • 没有。我按照您的建议修复了丢失的结构。现在我得到不同的错误。我用新错误更新了问题。
    猜你喜欢
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多