React test with jest 不支持来自 webpack 别名的 moduleNameMapper

IT技术 reactjs webpack jestjs enzyme blueprintjs
2021-05-22 15:26:13

我正在使用笑话和酶来测试我的react组件。我还使用蓝图图标作为我的react组件中的依赖项之一。作为我的 webpack 配置的一部分,添加了以下内容:

config.resolve.alias = {
    blueprintIcons: path.resolve('./node_modules/@blueprintjs/icons'),
    blueprint: path.resolve('./node_modules/@blueprintjs/core')
};

添加以下内容作为 jest 配置的一部分:

    rootDir: '.',
    roots: [
        '<rootDir>/__test__/'
    ],
    transformIgnorePatterns: [
        '<rootDir>/node_modules/'
    ],
    transform: {
        '^.+\\.jsx?$': 'babel-jest'
    },
    testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.jsx?$',
    moduleDirectories: ['node_modules'],
    moduleFileExtensions: [
        'js',
        'jsx',
        'json',
        'node'
    ],
    moduleNameMapper: {
        '\\.(css|scss)$': 'identity-obj-proxy',
        blueprintIcons: '<rootDir>/node_modules/@blueprintjs/core'
        blueprint: '<rootDir>/node_modules/@blueprintjs/core'
    },
    snapshotSerializers: ['enzyme-to-json/serializer']
};

这是我的组件:

import React, { Component } from 'react';
import Icon from 'blueprint';
import IconNames from 'blueprintIcons';
class Foo extends Component {
  render() {
      return (
        <div>
           <p>Hello Foo</p>
           <Icon icon={IconNames.HOME} iconSize={Icon.SIZE_LARGE}/>
        </div>
      );
  }
}
export default Foo;

这是我的 foo.test.js

import React from 'react';
import Foo from '../../src/Components/Foo';
import Adapter from 'enzyme-adapter-react-16';
import Enzyme, { mount, shallow } from 'enzyme';

describe('Reviews component', () => {
    it('render component when loading in progress', () => {
        const mountedComponent = mount(<Foo />);
    });
});

当我尝试测试该组件时,测试失败

类型错误:无法读取 IconNames.HOME 处未定义的属性“HOME”

这是我的 package.json 中指定的一些包

"babel-cli": "6.26.0",
"babel-core": "^6.26.3",
"babel-eslint": "^10.0.1",
"babel-jest": "^23.0.1",
"babel-loader": "7.1.4",
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.1.1",
"enzyme-to-json": "^3.3.4",
"jest": "^23.1.0",
"jest-html-reporter": "^2.3.0",
"@blueprintjs/core": "^2.3.1",
"react": "16.2.0"

我正在使用react 16.2.0

我试过嘲笑它但不起作用(也许我做错了)但这是我正在使用的代码:

jest.mock('@blueprintjs/icons', () => (
    { IconNames: {HOME: 'home' }}));
2个回答

我认为模拟是一种可能的解决方案 - 不确定为什么您的代码不起作用(可能是因为它不在default密钥内,或者模拟的名称不正确),但您可以尝试其他方法。

  1. 在您的 Jest 配置中,添加以下内容:
"setupFiles": [
    "./__mocks__/mockIcons.js"
],
  1. /__mocks__在根文件夹中创建文件夹
  2. 使用以下代码mockIcons.js在内部创建__mocks__
jest.mock("blueprint", () => ({
    default: {
        Icon: { SIZE_LARGE: 'large' }
    }
}))

jest.mock("blueprintIcons", () => ({
    default: {
        IconNames: { HOME: 'home' }
    }
}))

@blueprintjs/icons如果没有其他效果,请尝试用作模拟名称。

对我来说,以下解决方案有效:

在开玩笑的配置中:

moduleNameMapper: {
        '^blueprint': '<rootDir>/node_modules/@blueprintjs/core',
        '^@blueprintjs/(.*)$': '<rootDir>/node_modules/@blueprintjs/$1'
}

休息一切都保持不变。