首页 > 解决方案 > 反应单元测试 - Enzmye shallow

问题描述

我正在尝试在 React with Enzyme 中设置单元测试。当我运行命令“npm-test”时,测试失败。控制台终端指示由于 shallow() 而失败。我已经使用这个命令安装了酶 npm install --save 酶酶-适配器-反应-16 反应-测试-渲染器。有谁知道如何解决这个问题?

下面是组件

import React from 'react';

    class Login extends Component {
      render() {
        return <div><input
          onChange={(event) => {
             this.setState({input: event.target.value})}}
          type="text" /></div>;
      }
    }

    export default Login;

这是我为组件编写的单元测试。

import React from 'react';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

import Login from '../../../src/components/authentication/Login';
import Enzyme from 'enzyme';

configure({adapter: new Adapter()});

  it("should create an entry in component state with the event value", () => {
    // given
    const component = shallow(<Login/>);
    const form = component.find('input');
    // when
    form.props().onChange({target: {
      name: 'myName',
      value: 'myValue'
    }});
    // then
    expect(component.state('input')).toEqual('myValue');
  });

谢谢您的帮助。

标签: reactjsjsxenzyme

解决方案


嗨,也许你错过了约定:

您必须将测试文件放在一个__tests__目录中,并且测试文件应命名为:YourComponent.test.js

比将您的测试包装在测试套件中:

describe('Your test suite', () => {
  test('it should do something', () => {
   // the content of your test
  });
});

推荐阅读