如何在JEST中模拟$ .ajax调用

Nit*_*ila 8 reactjs jestjs react-router

我是React&JEST框架的新手,我尝试在下面做一个响应的ajax调用,如果我收到成功数据,它将重定向到主页,否则会显示一条错误消息.

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);
Run Code Online (Sandbox Code Playgroud)

反应代码正在工作,我试图在JEST中为ajax调用的上述代码编写一个单元测试,如下所示,

  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)
  });
Run Code Online (Sandbox Code Playgroud)

当我运行此测试用例时,我收到以下错误消息,我不知道上面的代码有什么问题.

预期使用Object调用的函数

谁能帮助我在单元测试脚本中找出问题.

小智 0

unmock方法删除了模拟,因此您需要使用 Jestmock方法代替。 Jest repo有几个示例描述了基本用法,包括如何模拟 jquery 以及如何与 React 一起使用,因此值得一看。