Nithila
Nithila

Reputation: 313

How to mock $.ajax call in JEST

I am new to React & JEST framework, I tried doing ajax call in react as below, if i receives a success data it will redirect to home page else an error message is displayed.

let params ={
    userName : this.state.userName,
    password : this.state.passWord
};

$.ajax({
    url: '/reactApp/login',
    dataType: 'json',
    contentType: 'application/json;',
    type: 'POST',
    data: JSON.stringify(params),
    success: function (successData) {
        if (typeof(Storage) !== "undefined") {
            localStorage.setItem('userProfile', JSON.stringify(successData));
            browserHistory.push('/reactApp/Home');
        } else {
            alert("The browser version is not supported.Please use Internet explorer 11, Chrome or firefox.")
        }
    }.bind(this),
    error: function(errorData){
        this.setState({
            errorMessage: errorData.message,
            errorDisplay: true,             
        });
    }.bind(this);

The react code is working, i tried to write an unit test in JEST for the above code for ajax call as below,

  jest.unmock('jquery');
  jest.unmock('./AjaxLogin');

  var $ = require('jquery');
  const Login = TestUtils.renderIntoDocument(<AjaxLogin />);
  expect(Login).toBeDefined();
  var handleClick = jest.genMockFunction();

  var button = TestUtils.findRenderedDOMComponentWithTag(Login, 'button');

  TestUtils.Simulate.click(button);

  Login.handleClick(); 
  expect($.ajax).toBeCalledWith({
     url: '/reactApp/login',
     dataType: 'json',
     contentType: 'application/json;',           
     type: 'POST',
     data: JSON.stringify({userName : 'testing', password : 'password'}),
     success: jasmine.any(Function),
     error: jasmine.any(Function)
  });

When i run this test case, i received an below error message, i don't know what is wrong in the above code.

Expected Function to be called with Object

can anyone please help me to identify the issue in unit test script.

Upvotes: 12

Views: 5688

Answers (1)

Alex
Alex

Reputation: 2174

unmock method removes mock so you need to use Jest mock method instead. Jest repo has several examples describing the basic usage including how to mock jquery as well as how to use with react so it is worth looking at.

Upvotes: 0

Related Questions