Jest 错误:测试套件无法运行,如何解决?

bie*_*ier 3 unit-testing reactjs jestjs

我正在为 reactjs 测试 Jest,尤其是快照测试。这是我的测试:

import React, { Component } from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import Hello from 'hello';

test('if am then return goodmorning', () => {

    const wrapper = shallow(
        <Hello timeofday="am">
            <strong>Hello World!</strong>
        </Hello>
    );

    expect(toJson(wrapper)).toMatchSnapshot();

});
Run Code Online (Sandbox Code Playgroud)

我正在测试的组件:

import React from 'react';

export default class Hello extends React.Component {

    constructor(props) {
        super();
        this.props = props;
        //todo remove
        console.log('testing props', props);
    }

    render() {
        let greet ;

        if (this.props) {
            greet= this.props.timeofday ==='am' ? 'morning' : 'evening'
        }
        return <h1>Good {greet}</h1>
    }
}
Run Code Online (Sandbox Code Playgroud)

当我从命令行运行 jest 时,出现此错误:

    jest

 FAIL  app/components/hello.test.js
  ? Test suite failed to run

    Cannot find module 'hello' from 'hello.test.js'

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
      at Object.<anonymous> (app/components/hello.test.js:4:14)

Test Suites: 1 failed, 1 total
Run Code Online (Sandbox Code Playgroud)

为什么我不能运行这个笑话?这里有什么问题?

sam*_*sam 5

在您的测试文件中,

import Hello from 'hello';
Run Code Online (Sandbox Code Playgroud)

应该改为

import Hello from './hello';
Run Code Online (Sandbox Code Playgroud)

或者你可以在 webpack 配置文件中设置路径。