Write unit test case for a react component

。_饼干妹妹 提交于 2020-02-16 07:45:19

问题


I am new to the react redux. I am trying to write a unit test case for a component search functionality which looks like,

constructor(props) {
        super(props);
        this.staate = {
            search : ''
        }
    }

     onInputChnage = (e) => {
    this.setState({ search: e.target.value });
  }

    render() {

       const { jobs: { content } } = this.props;
        const { search } = this.state;
        const filteredList = content.filter(job => (job.jdName && job.jdName.toLowerCase().includes(search.toLowerCase())) || (job.technology && job.technology.toLowerCase().includes(search.toLowerCase())));

        return (
            <input type="text"
                id="searchJob"
                className="form-control-sm border-0 flex-grow-1"
                value={this.state.search}
                placeholder="Technology / Job title"
                onChange={this.onInputChnage} />
              <i className="fa fa-search search-job"></i>
        )
    }
}

And the data is like,

this.props.jobs = {
  content: [
    {
      id: '5b7d4a566c5fd00507501051',
      companyId: null,
      jdName: 'Senior/ Lead UI Developer',
      jobDescription: null,
      technology: 'java'
    },
    {
      id: '5b7d4a566c5fd005075011',
      companyId: null,
      jdName: 'ead UI Developer',
      jobDescription: null,
      technology: 'angular'
    }
  ]
};

So, here I want to test this component search thing. I am using jest and enzymes for this . can anyone help me with this?


回答1:


Here is the solution:

index.tsx:

import React from 'react';

interface ISearchComponentOwnProps {
  jobs: { content: any };
}

interface ISearchComponentState {
  search: string;
}

export class SearchComponent extends React.Component<ISearchComponentOwnProps, ISearchComponentState> {
  constructor(props: ISearchComponentOwnProps) {
    super(props);
    this.state = {
      search: ''
    };
  }

  public render() {
    const {
      jobs: { content }
    } = this.props;
    const { search } = this.state;
    const filteredList = content.filter(
      job =>
        (job.jdName && job.jdName.toLowerCase().includes(search.toLowerCase())) ||
        (job.technology && job.technology.toLowerCase().includes(search.toLowerCase()))
    );

    return (
      <div>
        <input
          type="text"
          id="searchJob"
          className="form-control-sm border-0 flex-grow-1"
          value={this.state.search}
          placeholder="Technology / Job title"
          onChange={this.onInputChnage}
        />
        <i className="fa fa-search search-job"></i>

        <ul className="job-list">
          {filteredList.map(job => {
            return (
              <li key={job.id}>
                <span>jdName: {job.jdName}</span>
                <span>technology: {job.technology}</span>
              </li>
            );
          })}
        </ul>
      </div>
    );
  }

  private onInputChnage = (e: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ search: e.target.value });
  }
}

Unit test:

index.spec.tsx:

import React from 'react';
import { shallow } from 'enzyme';
import { SearchComponent } from '.';

describe('SearchComponent', () => {
  const jobs = {
    content: [
      {
        id: '5b7d4a566c5fd00507501051',
        companyId: null,
        jdName: 'Senior/ Lead UI Developer',
        jobDescription: null,
        technology: 'java'
      },
      {
        id: '5b7d4a566c5fd005075011',
        companyId: null,
        jdName: 'ead UI Developer',
        jobDescription: null,
        technology: 'angular'
      }
    ]
  };

  it('should search and filter job list correctly', () => {
    const wrapper = shallow(<SearchComponent jobs={jobs}></SearchComponent>);
    expect(wrapper.find('#searchJob')).toHaveLength(1);
    const mockedChangeEvent = { target: { value: 'Lead' } };
    expect(wrapper.state('search')).toBe('');
    wrapper.find('#searchJob').simulate('change', mockedChangeEvent);
    expect(wrapper.state('search')).toBe('Lead');
    expect(wrapper.find('.job-list').children()).toHaveLength(1);
    expect(wrapper.html()).toMatchSnapshot();
  });
});

Unit test result with 100% coverage:

 PASS  src/stackoverflow/54456606/index.spec.tsx
  SearchComponent
    ✓ should search and filter job list correctly (19ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.tsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 passed, 1 total
Time:        3.058s, estimated 5s

Component Snapshot:

// Jest Snapshot v1

exports[`SearchComponent should search and filter job list correctly 1`] = `"<div><input type=\\"text\\" id=\\"searchJob\\" class=\\"form-control-sm border-0 flex-grow-1\\" value=\\"Lead\\" placeholder=\\"Technology / Job title\\"/><i class=\\"fa fa-search search-job\\"></i><ul class=\\"job-list\\"><li><span>jdName: Senior/ Lead UI Developer</span><span>technology: java</span></li></ul></div>"`;

Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/54456606



来源:https://stackoverflow.com/questions/54456606/write-unit-test-case-for-a-react-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!