简体   繁体   中英

react unit testing - Enzmye shallow

I am trying to setup unit testing in React with Enzyme. When i run the command "npm-test" the test fails. The console terminal indicates that it failed because of shallow(). I have installed enzyme using this command npm install --save enzyme enzyme-adapter-react-16 react-test-renderer. Do anyone know how to solve this issue?

Below is the component

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;

This is the unit test i have written for the Component.

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

Thanks for the help.

Hi perhaps you miss the conventions:

you have to put your test files inside a __tests__ directory and tests file should be named: YourComponent.test.js

Than wrap your test within a test suite:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM