使用 nock 使用 mocha 测试 HTTP post 请求

Testing an HTTP post Request with mocha using nock

我正在学习如何在不连接到 API 的情况下测试前端 Web 应用程序。 我的问题是:我必须测试一个 POST HTTP 请求,但总是得到一个错误:TypeError: loginUser(...).then is not a function.

我知道我的期望不正确。我必须更改 JWT 令牌的数据,而且还不知道该怎么做。

这是一个简单的用户身份验证。 Http post 发送电子邮件和密码,取回 JWT(json 网络令牌)。我必须编写测试以确保我已发送正确的信息并获得 JWT 作为响应。

感谢您的帮助

这是我的代码:

//login.test.js

const expect = require('chai').expect;
const loginUser = require('../src/actions/authActions').loginUser;
const res = require('./response/loginResponse');
const nock = require('nock');
const userData = {
   email: 'test@test.com',
   password: '123456'
};

describe('Post loginUser', () => {
beforeEach(() => {
  nock('http://localhost:3000')
    .post('/api/users/login', userData )
    .reply(200, res);
});

it('Post email/pwd to get a token', () => {
    return loginUser(userData)
      .then(res => {
        //expect an object back
        expect(typeof res).to.equal('object');

        //Test result of name, company and location for the response
        expect(res.email).to.equal('test@test.com')
        expect(res.name).to.equal('Tralala!!!')
      });
  });
});


//authActions.js
import axios from "axios";
import setAuthToken from "../utils/setAuthToken";
import jwt_decode from "jwt-decode";
import {
  GET_ERRORS,
  SET_CURRENT_USER,
  USER_LOADING
} from "./types";

// Login - get user token
export const loginUser = userData => dispatch => {
axios
  .post("/api/users/login", userData)
  .then(res => {
    // Save to localStorage
    // Set token to localStorage
    const { token } = res.data;
    localStorage.setItem("jwtToken", token);
    // Set token to Auth header
    setAuthToken(token);
    // Decode token to get user data
    const decoded = jwt_decode(token);
    // Set current user
    dispatch(setCurrentUser(decoded));
  })
  .catch(err =>
    dispatch({
      type: GET_ERRORS,
      payload: err.response.data
    })
  );


// loginResponse.js
module.exports = { email: 'test@test.com',
password: '123456',
name: "Tralala!!!"
};

实际结果: 1) Post 登录用户 Post email/pwd 获取令牌: TypeError: loginUser(...).then 不是函数 在 Context.then (test/login.test.js:37:12)

您调用 loginUser 方法的方式不正确。此方法returns 另一个功能。因此,除了 loginUser(userData),您还必须指定 dispatch 参数,例如loginUser(userData)(dispatch).then()

我改变了方法在axios语句

之前指定return
export const loginUser = userData => dispatch => {
  return axios // adding return
    .post("/api/users/login", userData)
    .then(res => {
     ...
    })
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      })
    );
};

为了测试,我可能会涉及 Sinon 来监视 dispatch

it("Post email/pwd to get a token", () => {
  const dispatchSpy = sinon.spy();

  return loginUser(userData)(dispatchSpy).then(res => {
    //expect an object back
    expect(typeof res).to.equal("object");

    //Test result of name, company and location for the response
    expect(res.email).to.equal("test@test.com");
    expect(res.name).to.equal("Tralala!!!");
  });
});

希望对您有所帮助