为反应组件编写单元测试用例 [英] Write unit test case for a react component

查看:32
本文介绍了为反应组件编写单元测试用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 react redux 的新手.我正在尝试为组件搜索功能编写单元测试用例,

构造函数(道具){超级(道具);this.state = {搜索 : ''}}onInputChnage = (e) =>{this.setState({ 搜索: e.target.value });}使成为() {const { 工作:{ 内容 } } = this.props;const { 搜索 } = this.state;constfilteredList = content.filter(job => (job.jdName && job.jdName.toLowerCase().includes(search.toLowerCase())) || (job.technology && job.technology.toLowerCase().includes(search.toLowerCase())));返回 (<输入类型=文本"id="搜索工作"className="form-control-sm border-0 flex-grow-1"值={this.state.search}占位符=技术/职位"onChange={this.onInputChnage}/><i className="fa fa-search search-job"></i>)}}

数据就像,

this.props.jobs = {内容: [{id: '5b7d4a566c5fd00507501051',公司 ID:空,jdName: '高级/首席 UI 开发人员',工作描述:空,技术:'java'},{id: '5b7d4a566c5fd005075011',公司 ID:空,jdName: 'ead UI Developer',工作描述:空,技术:'角度'}]};

所以,在这里我想测试一下这个组件搜索的东西.我为此使用 jest 和酶.有人可以帮我吗?

解决方案

解决方案如下:

index.tsx:

从'react'导入React;接口 ISearchComponentOwnProps {工作:{内容:任何};}接口 ISearchComponentState {搜索:字符串;}导出类 SearchComponent 扩展了 React.Component{构造函数(道具:ISearchComponentOwnProps){超级(道具);this.state = {搜索: ''};}公共渲染(){常量{工作:{内容}} = this.props;const { 搜索 } = this.state;constfilteredList = content.filter(工作 =>(job.jdName && job.jdName.toLowerCase().includes(search.toLowerCase())) ||(job.technology && job.technology.toLowerCase().includes(search.toLowerCase())));返回 (<div><输入类型=文本"id="搜索工作"className="form-control-sm border-0 flex-grow-1"值={this.state.search}占位符=技术/职位"onChange={this.onInputChnage}/><i className="fa fa-search search-job"></i><ul className="job-list">{filteredList.map(job => {返回 (<li key={job.id}><span>jdName: {job.jdName}</span><span>技术:{job.technology}</span>);})}

);}private onInputChnage = (e: React.ChangeEvent) =>{this.setState({ 搜索: e.target.value });}}

单元测试:

index.spec.tsx:

从'react'导入React;从酶"导入{浅};从 '.' 导入 { SearchComponent };描述('搜索组件',()=> {常量工作 = {内容: [{id: '5b7d4a566c5fd00507501051',公司 ID:空,jdName: '高级/首席 UI 开发人员',工作描述:空,技术:'java'},{id: '5b7d4a566c5fd005075011',公司 ID:空,jdName: 'ead UI Developer',工作描述:空,技术:'角度'}]};it('应该正确搜索和过滤工作列表', () => {const wrapper = Shallow(<SearchComponent jobs={jobs}></SearchComponent>);期望(wrapper.find('#searchJob')).toHaveLength(1);const mockedChangeEvent = { target: { value: 'Lead' } };期望(wrapper.state('search')).toBe('');wrapper.find('#searchJob').simulate('change', mockedChangeEvent);期望(wrapper.state('search')).toBe('Lead');期望(wrapper.find('.job-list').children()).toHaveLength(1);期望(wrapper.html()).toMatchSnapshot();});});

100% 覆盖率的单元测试结果:

 PASS src/stackoverflow/54456606/index.spec.tsx搜索组件✓ 应该正确搜索和过滤工作列表(19 毫秒)-----------|----------|----------|----------|----------|--------------------|档案 |% stmts |% 分支 |% 函数 |% 行 |未覆盖的行#s |-----------|----------|----------|----------|----------|--------------------|所有文件 |100 |100 |100 |100 ||index.tsx |100 |100 |100 |100 ||-----------|----------|----------|----------|----------|--------------------|测试套件:通过 1 个,共 1 个测试:1 次通过,共 1 次快照:通过 1 个,共 1 个时间:3.058s,估计5s

组件快照:

//Jest 快照 v1export[`SearchComponent 应该正确搜索和过滤工作列表 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:高级/首席 UI 开发人员</span><span>技术:java</span></li></ul></div>"`;

这里是完整的演示:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/54456606

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?

解决方案

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

这篇关于为反应组件编写单元测试用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆