javascript - Jest 单元测试。模拟函数返回,监视函数调用

标签 javascript reactjs unit-testing jestjs

我正在使用 Jest 开发 React 应用程序

我必须测试组件的功能:

handleSubmit = event => {
  event && event.preventDefault();
  this.formValidation() ? this.login() : this.handleErrors(this.state);
};

您能告诉我如何模拟 this.formValidation 方法返回以监视 this.loginthis.handleErrors 吗?

  formValidation = () => {
    return (
      validateEmail(this.state.email) && isPasswordValid(this.state.password)
    );
  };

  login = () => {
    authenticationService.login(this.state.email, this.state.password).then(
      () => this.props.history.push({ pathname: "/template" }),
      message => this.setState({ errors: { api: message } })
    );
  };

  handleErrors = ({ email, password }) => {
    this.setState({
      errors: {
        email: !validateEmail(email) ? "Email is required" : null,
        password: !isPasswordValid(password)
          ? "Password is required. (7+ chars: mixed, number, special)"
          : null
      }
    });
  };

感谢您的帮助

最佳答案

这是单元测试解决方案:

index.jsx:

import React, { Component } from 'react';

class SomeComponent extends Component {
  constructor() {
    this.state = {};
  }
  handleSubmit = (event) => {
    event && event.preventDefault();
    this.formValidation() ? this.login() : this.handleErrors(this.state);
  };

  formValidation() {}

  handleErrors(state) {}

  login() {}

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}></form>
      </div>
    );
  }
}

export default SomeComponent;

index.test.jsx:

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

describe('59741487', () => {
  let wrapper;
  const mFormValidation = jest.fn();
  const mLogin = jest.fn();
  const mHandleErrors = jest.fn();
  beforeEach(() => {
    SomeComponent.prototype.formValidation = mFormValidation;
    SomeComponent.prototype.login = mLogin;
    SomeComponent.prototype.handleErrors = mHandleErrors;
    wrapper = shallow(<SomeComponent></SomeComponent>);
  });
  afterEach(() => {
    jest.clearAllMocks();
  });
  it('should render', () => {
    expect(wrapper.find('form')).toBeTruthy();
  });
  describe('#handleSubmit', () => {
    it('should login', () => {
      mFormValidation.mockReturnValueOnce(true);
      const mEvent = { preventDefault: jest.fn() };
      wrapper.find('form').simulate('submit', mEvent);
      expect(mEvent.preventDefault).toBeCalledTimes(1);
      expect(mLogin).toHaveBeenCalledTimes(1);
    });

    it('should handle error', () => {
      mFormValidation.mockReturnValueOnce(false);
      const mEvent = { preventDefault: jest.fn() };
      wrapper.find('form').simulate('submit', mEvent);
      expect(mEvent.preventDefault).toBeCalledTimes(1);
      expect(mHandleErrors).toBeCalledWith({});
    });
  });
});

带有覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/59741487/index.test.jsx (13.687s)
  59741487
    ✓ should render (12ms)
    #handleSubmit
      ✓ should login (2ms)
      ✓ should handle error (3ms)

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |    57.14 |      100 |                   |
 index.jsx |      100 |      100 |    57.14 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        15.854s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59741487

关于javascript - Jest 单元测试。模拟函数返回,监视函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59741487/

相关文章:

javascript - 如何将列表映射到一定数量的数据

javascript - Sweet Alert 中使用 JSX 代替 HTML

javascript - 无论如何显示错误路线

javascript - 如何在 Meteor 中设置事件目标的文本和颜色?

unit-testing - 在 Jest 测试中获得 axios 响应后如何重新渲染

ios - 无法在 iOS 设备上运行单元测试

unit-testing - Spring JsonView 的单元测试

ASP.NET - 你如何对 WebControls 进行单元测试?

javascript - AngularJS $http.post 内部函数

javascript - 使用正则表达式获取最后两个斜杠或其他最后两个相同字符之间的任何字符串?