【问题标题】:React Jest test didn't recognize import AliasReact Jest 测试无法识别导入别名
【发布时间】:2019-05-08 13:31:20
【问题描述】:

我正在 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)

Jest 测试文件:

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();
  }); 
});

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

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

    1. 告诉 Jest 如何解决您的文件:
      • 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
    

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 2015-07-31
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      相关资源
      最近更新 更多