简体   繁体   中英

How to test function that we get from action, has been called?

So I was trying to create a unit test using jest in ReactJS. The Unit test itself just to verify if the function (from action) has been called

I already tried to mock the function, but the result tells that I must mock the function

Here the code of the function that I want to create a unit test

import { testfunction } from '../../actions/auth';

handleSubmit(userParams) {
    this.setState({ form: { ...this.state.form, isFetching: true } });
    this.props.dispatch(testfunction(userParams,
      this.successCallback.bind(this), this.errorCallback.bind(this)));
  }

and for the unit test

import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import Login from '../../../components/auth/Login';

const mockStore = configureStore([thunk]);
const initialState = {
  history: { },
};
const store = mockStore(initialState);
let wrapper;
let history;
let testfunction;
beforeEach(() => {
  testfunction= jest.fn();
  history = { push: jest.fn() };
  wrapper = shallow(
    <Login
      history={history}
      store={store}
      testfunction={testfunction}
    />
  );
});

describe('handleSubmit()', () => {
    test('should call testfunction props', () => {
      const component = wrapper.dive();
      const instance = component.instance();
      const sampleUserParams = {
        email: 'test@test.com',
        password: 'samplePassword123',
      };
      instance.handleSubmit(sampleUserParams);

      expect(testfunction).toHaveBeenCalled();
    });
});

I just want to check if the "testfunction" is called when I called handleSubmit function. But the error message is:

"Expected mock function to have been called."

it feels my way to mock the function is wrong. Does anyone know how to correct way to test that function?

Here is the solution:

index.tsx :

import React, { Component } from 'react';
import { testfunction } from './testfunction';

class Login extends Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {
      form: {}
    };
  }

  public render() {
    const userParams = {};
    return (
      <div className="login">
        <form onSubmit={() => this.handleSubmit(userParams)}>some form</form>
      </div>
    );
  }

  private handleSubmit(userParams) {
    this.setState({ form: { ...this.state.form, isFetching: true } });
    this.props.dispatch(testfunction(userParams, this.successCallback.bind(this), this.errorCallback.bind(this)));
  }

  private successCallback() {
    console.log('successCallback');
  }
  private errorCallback() {
    console.log('errorCallback');
  }
}

export { Login };

testFunction.ts :

async function testfunction(userParams, successCallback, errorCallback) {
  return {
    type: 'ACTION_TYPE',
    payload: {}
  };
}
export { testfunction };

Unit test:

import React from 'react';
import { shallow } from 'enzyme';
import { Login } from './';
import { testfunction } from './testfunction';

jest.mock('./testfunction.ts');

describe('Login', () => {
  const dispatch = jest.fn();
  const sampleUserParams = {
    email: 'test@test.com',
    password: 'samplePassword123'
  };
  it('handleSubmit', () => {
    const wrapper = shallow(<Login dispatch={dispatch} />);
    expect(wrapper.is('.login')).toBeTruthy();
    expect(wrapper.find('form')).toHaveLength(1);
    wrapper.find('form').simulate('submit');
    const cmpInstance = wrapper.instance();

    expect(dispatch).toBeCalledWith(
      // tslint:disable-next-line: no-string-literal
      testfunction(sampleUserParams, cmpInstance['successCallback'], cmpInstance['errorCallback'])
    );
    // tslint:disable-next-line: no-string-literal
    expect(testfunction).toBeCalledWith(sampleUserParams, cmpInstance['successCallback'], cmpInstance['errorCallback']);
  });
});

Unit test with coverage report:

 PASS  src/stackoverflow/57847401/index.spec.tsx
  Login
    ✓ handleSubmit (22ms)

-----------------|----------|----------|----------|----------|-------------------|
File             |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------------|----------|----------|----------|----------|-------------------|
All files        |    86.36 |      100 |     62.5 |       85 |                   |
 index.tsx       |       90 |      100 |    71.43 |    88.89 |             27,30 |
 testfunction.ts |       50 |      100 |        0 |       50 |                 2 |
-----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.201s, estimated 4s

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

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