小编Nit*_*ila的帖子

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

我是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 …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs react-router

8
推荐指数
1
解决办法
2605
查看次数

如何在JEST中模拟localStorage.setIem和localStorage.removeItem

当我试图模仿如下的笑话中的反应组件的localStorage时,

spyOn(window.localStorage,'removeItem');
window.localStorage.removeItem("key1");
window.localStorage.removeItem("key2");
expect(window.localStorage.removeItem).toHaveBeenCalledWith("key1");
expect(window.localStorage.removeItem).toHaveBeenCalledWith("key2");
Run Code Online (Sandbox Code Playgroud)

并使用以下代码进行localStorage模拟

let localStorageMock = (function() {
  var storage = {};

  return {
    setItem: function(key, value) {
      storage[key] = value || '';
    },
    getItem: function(key) {
      return storage[key] || null;
    },
    removeItem: function(key) {
      delete storage[key];
    },
    get length() {
      return Object.keys(storage).length;
    },
    key: function(i) {
      var keys = Object.keys(storage);
      return keys[i] || null;
    }
  };
})();
Object.defineProperty(window, 'localStorage', { value: localStorageMock });
Run Code Online (Sandbox Code Playgroud)

javascript reactjs jestjs

6
推荐指数
1
解决办法
3103
查看次数

模拟 axios 时无法读取 JEST 中未定义的属性“baseURL”

我尝试在 React 组件中使用 AXIOS 进行 ajax 调用,如下所示,

    let that = this;
    this.serverRequest = axios({
        url: '/login',
        method: 'post',
        data: JSON.stringify({ userName: "testing", passWord: "passWord" }),
        headers: {
            "Content-Type": 'application/json; charset=utf-8'
        }
    }).then(function (successData) {                    
            localStorage.setItem('userData', JSON.stringify(successData.data));
            this.setState({
                successMsge: "Valid credentials"
            });
        }).catch(function(errorData){                   
            this.setState({
                errorMessage: errorData.data.message,
                errorDisplay: true
            });
        }.bind(that));
Run Code Online (Sandbox Code Playgroud)

React 组件工作完美,当我尝试在 JEST 中模拟上述组件时,会显示错误。

我附上了下面的 JEST 代码,

expect(axios).toBeCalledWith({
    type: 'POST',
    baseURL: '/login',
    data: JSON.stringify(dataParams),
    headers: {
        "Content-Type": 'application/json; charset=utf-8'
    }
});
Run Code Online (Sandbox Code Playgroud)

当我运行 npm jest 时,我收到上述组件的以下错误

  - TypeError: Cannot read property 'baseURL' …
Run Code Online (Sandbox Code Playgroud)

reactjs jestjs axios

5
推荐指数
0
解决办法
1301
查看次数

标签 统计

jestjs ×3

reactjs ×3

axios ×1

javascript ×1

react-router ×1