【问题标题】:Error running a Jest snapshot test using a custom snapshot serializer - jest-styled-components使用自定义快照序列化程序运行 Jest 快照测试时出错 - jest-styled-components
【发布时间】:2020-05-04 17:23:53
【问题描述】:

我有一个使用 Create-React-app 构建的 react 应用程序。我正在尝试使用内联快照测试向其中一个组件添加单元测试。除了通常的嫌疑人之外,我还安装了 styled-componentsjest-styled-componentsPrettier 作为开发依赖项。我已将“jest-styled-components”作为 snapshotSerializer 添加到 package.json 中的 jest 配置中。

我在运行单元测试时遇到以下错误 -

    PrettyFormatPluginError: plugins[p].test is not a functionTypeError: plugins[p].test is not a function

  15 |   );
  16 | 
> 17 |   expect(container).toMatchInlineSnapshot();
     |                     ^
  18 | });
  19 | 
  20 | test("it renders empty cart message", () => {

  at findPlugin (node_modules/pretty-format/build/index.js:343:22)
  at prettyFormat (node_modules/pretty-format/build/index.js:523:22)
  at Object.toMatchInlineSnapshot (node_modules/expect/build/index.js:342:33)
  at Object.<anonymous> (src/components/cart-dropdown/__tests__/cart-dropdown.js:17:21)

我不知道出了什么问题。请帮忙。

// package.json
...
"devDependencies": {
        "@testing-library/dom": "^6.11.0",
        "@testing-library/jest-dom": "^5.0.0",
        "@testing-library/react": "^9.4.0",
        "jest-styled-components": "^7.0.0",
        "prettier": "^1.19.1"
      },
      "jest": {
        "snapshotSerializers": [
          "jest-styled-components"
        ]
      }

// unit test
import React from "react";
import { render } from "@testing-library/react";
import CartDropdown from "../cart-dropdown";

test("it renders", () => {
  const mockHistory = jest.fn();
  const mockDispatch = jest.fn();

  const { container, debug } = render(
    <CartDropdown
      cartItems={[]}
      history={mockHistory}
      dispatch={mockDispatch}
    />
  );

  expect(container).toMatchInlineSnapshot();
});

【问题讨论】:

    标签: reactjs unit-testing jestjs styled-components snapshot


    【解决方案1】:

    从 jest 配置中删除 snapshotSerializers 条目并将 jest-styled-components 导入添加到测试文件中解决了此问题。

    // unit test
    import React from "react";
    import { render } from "@testing-library/react";
    import CartDropdown from "../cart-dropdown";
    
    //add the below and remove entry for snapshotSerializers in jest config
    import 'jest-styled-components'
    
    test("it renders", () => {
      const mockHistory = jest.fn();
      const mockDispatch = jest.fn();
    
      const { container, debug } = render(
        <CartDropdown
          cartItems={[]}
          history={mockHistory}
          dispatch={mockDispatch}
        />
      );
    
      expect(container).toMatchInlineSnapshot();
    });
    

    【讨论】:

      【解决方案2】:

      从 jest config (Package.json) 错误中删除 snapshotSerializers 条目将消失

      【讨论】:

        猜你喜欢
        • 2018-12-13
        • 2018-11-27
        • 2017-08-13
        • 2018-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多