使用Jest,酶

时间:2020-01-11 10:05:45

标签: reactjs typescript testing

大家好。 我正在通过尝试从官方React页面复制示例项目之一来学习React和React Testing。 https://github.com/jeffersonRibeiro/react-shopping-cart

我偶然发现了一个问题。专门进行测试。 当我尝试为App Component复制测试代码时 https://github.com/jeffersonRibeiro/react-shopping-cart/blob/master/src/components/App/tests/App.test.js

import Root from '../../../Root';
import App from '../';

import Shelf from '../../Shelf';
import FloatCart from '../../FloatCart';

let wrapped;

beforeEach(() => {
  wrapped = mount(
    <Root>
      <App />
    </Root>
  );
});

afterEach(() => {
  wrapped.unmount();
});

it('shows a shelf', () => {
  expect(wrapped.find(Shelf).length).toEqual(1);
});

it('shows a floating cart', () => {
  expect(wrapped.find(FloatCart).length).toEqual(1);
});

它抛出一个错误,即“提取方法未定义”。我知道我需要使用该库来模拟提取,但是为什么它不会在原始代码中引发错误?唯一的区别是我正在使用Typescript。 如果我将mount()更改为shallow(),则可以正常工作。 如果我将尝试在其他测试中模拟redux的状态,则该测试仍在尝试获取数据并抛出错误“ fetch method is undefined”。 您能指出我所缺少的吗? 谢谢。

tsconfig.json

  {
      "compilerOptions": {
        "jsx": "react",
        "target": "es6",
        "outDir": "./build/",
        "noImplicitAny": false,
        "preserveConstEnums": true,
        "removeComments": true,
        "sourceMap": true,
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "allowSyntheticDefaultImports": true
      },
      "exclude": [
        "node_modules"
      ]
    }

jest.config

 module.exports = {
      "roots": [
        "<rootDir>/src"
      ],
      "transform": {
        "^.+\\.tsx?$": "ts-jest"
      },
      "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
      "moduleFileExtensions": [
        "ts",
        "tsx",
        "js",
        "jsx",
        "json",
        "node"
      ],
      "moduleNameMapper": {
        // "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.ts",
        "\\.(scss|sass|css|less)$": "identity-obj-proxy"
      },
      "snapshotSerializers": ["enzyme-to-json/serializer"],
      "setupFilesAfterEnv": ["<rootDir>/src/setupEnzyme.ts"],
    }

0 个答案:

没有答案