Pavan Pakki
Pavan Pakki

Reputation: 35

How to test Ajax call using Jest?

I want to test the below code using Jest.

class Login extends React.Component {
    getData() {
        $.ajax({
            type: "GET",
            url: myURL,
            success: function(data) {
                //some stuff with data
            },
            error :function(){
                alert("ERROR");
            }
        });
    }

    render() {
        return(
            //some stuff
        );
    }
}
export default Login;

How to test the Ajax call using jest? I also want the code coverage report of the above code.

Thanks in advance.

Upvotes: 2

Views: 5648

Answers (1)

Lin Du
Lin Du

Reputation: 102237

Here is my solution, I made a few refactorings for your code for testing easily.

index.tsx, the component code:

import React from 'react';
import $ from 'jquery';

class Login extends React.Component {
  constructor(props) {
    super(props);
    this.handleError = this.handleError.bind(this);
    this.handleSuccess = this.handleSuccess.bind(this);
  }
  public getData() {
    const myURL = 'https://github.com/mrdulin';
    $.ajax({
      type: 'GET',
      url: myURL,
      success: this.handleSuccess,
      error: this.handleError
    });
  }

  public render() {
    return <div>Login</div>;
  }

  private handleSuccess(data) {
    console.log(data);
  }

  private handleError() {
    alert('ERROR');
  }
}
export default Login;

index.spec.tsx, the unit test using jestjs and enzyme

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

describe('Login', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  test('should get data', async () => {
    const ajaxSpy = jest.spyOn($, 'ajax');
    const wrapper = shallow(<Login></Login>);
    const instance = wrapper.instance();
    (instance as any).getData();
    expect(wrapper.text()).toBe('Login');
    expect(ajaxSpy).toBeCalledWith({
      type: 'GET',
      url: 'https://github.com/mrdulin',
      // tslint:disable-next-line: no-string-literal
      success: instance['handleSuccess'],
      // tslint:disable-next-line: no-string-literal
      error: instance['handleError']
    });
  });

  test('handleSuccess', () => {
    const logSpy = jest.spyOn(console, 'log');
    const wrapper = shallow(<Login></Login>);
    const instance = wrapper.instance();
    // tslint:disable-next-line: no-string-literal
    instance['handleSuccess']('some data');
    expect(logSpy).toBeCalledWith('some data');
  });

  test('handleError', () => {
    window.alert = jest.fn();
    const wrapper = shallow(<Login></Login>);
    const instance = wrapper.instance();
    // tslint:disable-next-line: no-string-literal
    instance['handleError']();
    expect(window.alert).toBeCalledWith('ERROR');
  });
});

Unit test result with 100% coverage:

 PASS  src/stackoverflow/58306745/index.spec.tsx (8.183s)
  Login
    ✓ should get data (27ms)
    ✓ handleSuccess (3ms)
    ✓ handleError (1ms)

some data
-----------|----------|----------|----------|----------|-------------------|
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:       3 passed, 3 total
Snapshots:   0 total
Time:        9.545s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58306745

Upvotes: 1

Related Questions