【问题标题】:TypeError: Cannot destructure property 'enqueueSnackbar'TypeError:无法解构属性“enqueueSnackbar”
【发布时间】:2022-01-16 18:56:49
【问题描述】:

我有一个 Jest 单元测试,它正在测试来自模拟 API 调用的错误,以确保错误消息显示在页面上。在我的实际文件中,我使用notistack 来显示错误消息。我没有显示完整的 API 请求,因为我认为它不相关,简而言之,如下:

myComponent.js

import { useSnackbar } from 'notistack';

const myComponent = props => {
  const { enqueueSnackbar } = useSnackbar()

  //make an API call to an endpoint
  ...
  if (response.ok) enqueueSnackbar("API Success", { variant: "success" });
  else enqueueSnackbar("API Failed", { variant: "error" });
}

因此,我正在单元测试中测试上述内容。同样,我不会粘贴整个单元测试,因为我认为它不相关,但类似于:

myComponent.test.js

import { render, screen } from "@testing-library/react"

test("testing error message on API call", async () => {
  // mock the API call to return a 500 <- this works fine

  render(<myComponent />)

  // ensure that the error message is displayed in the screen
  expect(screen.queryByText(/API Failed/)).toBeInTheDocument();
});

执行上述操作,我得到一个错误:

TypeError: 无法解构 '(0 , _notistack.useSnackbar)(...)' 因为它是未定义的

如果我简单地包含以下内容,enqueueSnackbar() 将被定义,但测试仍然失败,因为消息是 null

const mockEnqueue = jest.fn();

jest.mock('notistack', () => ({
  ...jest.requireActual('notistack'),
  useSnackbar: () => {
    return {
      enqueueSnackbar: mockEnqueue
    };
  }
}));

但是,我什至不想模拟快餐栏,因为我想测试每个特定场景(有多个)的实际显示消息。

【问题讨论】:

    标签: javascript reactjs unit-testing jestjs notistack


    【解决方案1】:

    在我的单元测试中用SnackbarProvider 包装render() 解决了这个问题。

    import { SnackbarProvider } from "notistack"
    import { render, screen } from "@testing-library/react"
    
    test("testing error message on API call", async () => {
      /* mock the API call to return a 500 <- this works fine */
    
      render(
        <SnackbarProvider>
          <myComponent />
        </SnackbarProvider>
      )
    
      /* ensure that the error message is displayed in the screen */
      expect(screen.queryByText(/API Failed/)).toBeInTheDocument();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-30
      • 2020-10-07
      • 2021-03-21
      • 1970-01-01
      • 2020-01-21
      • 2020-05-28
      • 1970-01-01
      相关资源
      最近更新 更多