React Jest测试无法识别导入别名

时间:2019-05-08 13:31:21

标签: reactjs jestjs enzyme

我正在Button组件中执行基本的React Jest测试,并且该测试无法识别导入。

有人知道为什么这次导入测试失败吗?

组件:

import ...
import ... from 'styled-components';
import ... from 'styled-tools';

import {Icon} from 'xpto';
import {Default as theme} from 'Themes';

import * as mixins from '../../../config/styles/mixins';
... 
&:hover{
    background-color: #000;
    border: 1px solid ${theme.colors.primary};
    color: ${theme.colors.primary};
    & svg:not([fill="none"]):not([fill="#000"]) {
      fill: ${theme.colors.primary};
    }
    & .nohover svg {
      fill: ${({color}) => color};
    }
...

错误:

FAIL  .../Button/index.test.js
  ● Test suite failed to run

    Cannot find module 'Themes' from 'index.js'

       5 | 
       6 | import {Icon} from 'xpto';
    >  7 | import {Default as theme} from 'Themes';
         | ^
       8 | 
       9 | import * as mixins from '../../../config/styles/mixins';
      10 | 

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:221:17)
      at Object.<anonymous> (.../Button/index.js:7:1)

最佳测试文件:

import React from 'react';
import { mount } from 'enzyme';
import Button from './index';
describe('Button', () => {  
  it('should render correctly with no props', () => {
    const component = mount(<Button/>); 
    expect(component).toMatchSnapshot();
  }); 
});

1 个答案:

答案 0 :(得分:0)

Jest无法解析Themes文件夹中的index.js。您可以使用以下两种方法之一对其进行修复:

  1. 告诉玩笑如何解析文件:
    • 在package.json中设置
"jest": {
   "modulePaths": ["path to src folder which contains Themes folder"],
   ...
}

签出this tutorial

  1. 在.env文件中设置NODE_PATH
NODE_PATH=src/ # src folder contains Themes folder
相关问题