我正在学习如何测试前端Web应用程序不会对API的任何连接。我的问题是:我一定要考一个POST HTTP请求,但总是得到一个错误:类型错误:loginUser(...),那么是不是一个函数。
我知道我的期待是不正确的。我必须更改数据的JWT令牌,也还不知道热做到这一点。
这是一个简单的用户身份验证。 HTTP POST发送一个电子邮件地址和密码,取回一个JWT(JSON网络令牌)。我必须写一个测试,以确保我发送正确的信息,并得到了智威汤逊的响应。
谢谢你的帮助
这里是我的代码:
//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: '[email protected]',
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('[email protected]')
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: '[email protected]',
password: '123456',
name: "Tralala!!!"
};
实际结果:1)邮政loginUser发表电子邮件/密码来获得令牌:类型错误:loginUser(...),那么是不是在Context.then功能(测试/ login.test.js:37:12)
你叫loginUser
方法的方法是不正确的。该方法返回另一个函数。所以,与其loginUser(userData)
,还必须指定dispatch
参数例如loginUser(userData)(dispatch).then()
。
我改变指定return
语句之前axios
方法
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("[email protected]");
expect(res.name).to.equal("Tralala!!!");
});
});
希望能帮助到你