【问题标题】:Storybook: ReferenceError: jest is not definedStorybook: ReferenceError: jest is not defined
【发布时间】:2020-06-14 17:42:03
【问题描述】:

我在 Jest-enzyme 上构建了大约 8-9 个单元测试,并在 storybook 上运行。 所有这些测试都使用 jest cli 运行并成功通过,但使用 storybook 时会抛出错误。

jest is not defined
ReferenceError: jest is not defined
    at Module.<anonymous> (http://localhost:9010/main.b25dbb30a24ed968ce5a.bundle.js:596:1)
    at Module../src/components/__tests__/inspectionType.stories.js (http://localhost:9010/main.b25dbb30a24ed968ce5a.bundle.js:620:30)
    at __webpack_require__ (http://localhost:9010/runtime~main.b25dbb30a24ed968ce5a.bundle.js:785:30)
    at fn (http://localhost:9010/runtime~main.b25dbb30a24ed968ce5a.bundle.js:151:20)
    at webpackContext (http://localhost:9010/main.b25dbb30a24ed968ce5a.bundle.js:444:9)
    at http://localhost:9010/main.b25dbb30a24ed968ce5a.bundle.js:31:34
    at Array.forEach (<anonymous>)
    at loadStories (http://localhost:9010/main.b25dbb30a24ed968ce5a.bundle.js:31:14)
    at http://localhost:9010/vendors~main.b25dbb30a24ed968ce5a.bundle.js:5951:24
    at render (http://localhost:9010/vendors~main.b25dbb30a24ed968ce5a.bundle.js:3965:13)

现在当我进入故事时inspectionType.stories.js 代码是-

import React, { useState as useStateMock } from "react";
import expect from "expect";
import { mount } from "enzyme";
// import jest from "jest";

import { storiesOf, describe, it, specs } from "../../../.storybook/facade";

import Root from "../../root";
import InspectionType from "../instant-inspection/inspectionType";
import consumerSchema from "./mock-consumer-schema.json";
import "../instant-inspection/index.scss";

const getElement = () => {
  return (
    <Root>
      <InspectionType />
    </Root>
  );
};

jest.mock("react", () => ({   //The part throwing error//
  ...jest.requireActual("react"),
  useState: jest.fn(),
}));

storiesOf("Inspection Type Page", module).add("Inspection Type component", () => {
  specs(() =>
    describe("Inspection page", () => {
      localStorage.setItem("consumerSchemaSelected", JSON.stringify(consumerSchema));
      const setState = jest.fn();
      useStateMock.mockImplementation((init) => [init, setState]);
      it("should render a primary button to open a sample report", () => {
        const wrapper = mount(getElement());

        expect(
          wrapper
            .find(".primary")
            .at(0)
            .text()
        ).toEqual(" VIEW SAMPLE REPORT");
      });

      it("should render a button with text buy now", () => {
        const wrapper = mount(getElement());

        expect(
          wrapper
            .find(".primary")
            .at(1)
            .text()
        ).toEqual("Buy Now");
      });

      it("Should simulate a state change on buy now button", () => {
        const wrapper = mount(getElement());

        wrapper
          .find(".primary")
          .at(1)
          .props()
          .onClick();

        expect(setState).toHaveBeenCalledWith(true);
      });
    })
  );
  return getElement();
});

如果我尝试导入现在评论故事书的 jest 不会构建并引发错误 -

ERROR in ./node_modules/jest-worker/build/workers/NodeThreadsWorker.js
Module not found: Error: Can't resolve 'worker_threads' in 'C:\Users\ATIN\Desktop\client master\client-2.0\react-ui\node_modules\jest-worker\build\workers'
 @ ./node_modules/jest-worker/build/workers/NodeThreadsWorker.js 29:15-40
 @ ./node_modules/jest-worker/build/WorkerPool.js
 @ ./node_modules/jest-worker/build/index.js
 @ ./node_modules/@jest/core/node_modules/jest-haste-map/build/index.js
 @ ./node_modules/@jest/core/node_modules/jest-runtime/build/index.js
 @ ./node_modules/@jest/core/node_modules/jest-jasmine2/build/index.js
 @ ./node_modules/@jest/core/node_modules/jest-config/build/normalize.js
 @ ./node_modules/@jest/core/node_modules/jest-config/build/index.js
 @ ./node_modules/@jest/core/build/SearchSource.js
 @ ./node_modules/@jest/core/build/jest.js
 @ ./node_modules/jest/build/jest.js
 @ ./src/components/__tests__/inspectionType.stories.js
 @ ./src/components sync \.stories\.js$
 @ ./.storybook/config.js
 @ multi ./node_modules/@storybook/core/dist/server/common/polyfills.js ./node_modules/@storybook/core/dist/server/preview/globals.js ./.storybook/config.js ./node_modules/webpack-hot-middleware/client.js?reload=true&quiet=true

一直在想办法解决这个错误,但我卡住了。

编辑:我通过导入 import "jest-enzyme"; 解决了错误 Jest 未定义,但现在我得到期望未定义。即使我已经导入了 expect。

【问题讨论】:

  • 我有点困惑,你为什么要从故事书中开玩笑?这对我来说毫无意义。它们是两个不同的东西。一种用于在反应组件上运行单元测试,另一种用于轻松可视化组件。我错过了什么?
  • @JoeLloyd 我需要使用jest.mock 来模拟反应的useState 钩子。由于某些原因,我不能使用 react-testing-library。
  • 为什么要在 Storybook 中运行测试?不要在故事书中模拟 useState。让你的故事顺势而为。否则有什么意义,你不能使用交互。
  • @JoeLloyd 这些是开玩笑的普通单元测试用例。我只想跑过去看看他们的故事书。我需要将它们分开吗?我做错了吗?
  • 将它们分开,但添加参数jest: ['ComponentName'] 内幕。并确保您的故事书配置中有@storybook/addon-jest

标签: reactjs jestjs enzyme storybook


【解决方案1】:

尝试执行 Joe Lloyd 建议的操作,将 @storybook/addon-jest 添加到您的配置文件中,并且应该这样做。

# config.js
import { withTests } from '@storybook/addon-jest';

...

addDecorator(withTests({ results, filesExt: '\\.(test|story).tsx?$' }));

对于那些说不应该使用笑话并且不将其与故事混合的人,在某些情况下是需要的,例如:

<Parent>
  <Child/> <--- consumes useSomeRandomHook()
</Parent>

在这种情况下,如果您想避免道具钻探,您需要一种方法来模拟 useSomeRandomHook 返回的值。

【讨论】:

  • 我的测试中的模拟似乎不会影响我的故事。
猜你喜欢
  • 2021-03-29
  • 2019-12-02
  • 1970-01-01
  • 2014-03-03
  • 2020-08-14
  • 2021-03-19
  • 2018-12-26
  • 2019-02-08
  • 2015-11-19
相关资源
最近更新 更多