Reactjs 如何开玩笑地模拟$.ajax调用

Reactjs 如何开玩笑地模拟$.ajax调用,reactjs,react-router,jestjs,Reactjs,React Router,Jestjs,我是React&JEST框架的新手,我尝试在React中执行ajax调用,如下所示,如果我收到成功数据,它将重定向到主页,否则将显示错误消息 let params ={ userName : this.state.userName, password : this.state.passWord }; $.ajax({ url: '/reactApp/login', dataType: 'json', contentType: 'application/j

我是React&JEST框架的新手,我尝试在React中执行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);
react代码正在运行,我试图为上述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)
  });
jest.unmack('jquery');
开玩笑的unmack('./AjaxLogin');
var$=require('jquery');
const Login=TestUtils.renderIntoDocument();
expect(Login.toBeDefined();
var handleClick=jest.genMockFunction();
var button=TestUtils.findrenderedomcomponentwithtag(登录名,'button');
TestUtils.Simulate.click(按钮);
Login.handleClick();
期望($.ajax).toBeCalledWith({
url:“/reactApp/login”,
数据类型:“json”,
contentType:'应用程序/json;',
键入:“POST”,
数据:JSON.stringify({userName:'testing',password:'password'}),
成功:茉莉。任何(功能),
错误:jasmine.any(函数)
});
当我运行这个测试用例时,我收到了下面的错误消息,我不知道上面的代码中有什么错误

应使用对象调用函数


任何人都可以帮助我识别单元测试脚本中的问题。

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