【问题标题】:react unit testing - Enzmye shallow反应单元测试 - 酶浅
【发布时间】:2018-05-02 13:11:39
【问题描述】:

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

下面是组件

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

感谢您的帮助。

【问题讨论】:

  • 那么实际的错误信息是什么?
  • 酶适配器反应 16 可能存在一些问题。看起来他们有 311 个未解决的问题:github.com/airbnb/enzyme/… 我用 15.4 运行了你的代码,没有任何问题。

标签: reactjs jsx enzyme


【解决方案1】:

嗨,也许你错过了约定:

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

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

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

【讨论】:

  • 嗨,我尝试将登录名和 Login.test.js 放在同一个文件夹中,现在我收到此错误 ● 测试套件无法运行 ReferenceError: Component is not defined at Object. (src/ components/authentication/Login.js:3:21) 在 Object. (src/components/authentication/Login.test.js:5:14) 在 在 process._tickCallback (internal/process/next_tick. js:188:7)
  • Peharps 您没有在组件中定义 Componentimport React, { Component } from 'react'
  • 我忘记添加 import React, { Component } from 'react';
  • 好的,这很容易解决
  • 感谢您的帮助。我在这上面花的时间太长了;(
猜你喜欢
  • 2017-09-24
  • 2020-11-17
  • 1970-01-01
  • 2019-01-30
  • 2018-03-23
  • 1970-01-01
  • 2019-03-25
  • 2020-08-26
  • 2018-10-14
相关资源
最近更新 更多