我正在使用NodeJS和KOA创建一个API。为了进行测试,我使用chai(chai-http)和mocha。
当我在控制器中使用const { username } = ctx.state.user
来获取发送请求的用户的用户名时,就会出现问题。使用我的应用程序(使用Flutter)或Postman访问它们时,它可以工作,但是使用mocha运行测试时,出现错误TypeError: Cannot destructure property 'username' of 'undefined' or 'null'
。调试代码时,我发现ctx
有一个state
的键,但是该键的值为空。我尝试了方法.set(...)
和.send(...)
,但它们只修改了ctx.request.header
和ctx.request.body
内部的值。
所以我的问题是:是否可以使用chai为ctx.state
设置一个值,如果可以,如何设置?我想输入类似{user: {username: 'chai'}}
的内容。
这是两个主要部分,要测试的控制器部分和测试方法:
async function bar(ctx,next) {
const { username } = ctx.state.user;
const { value } = ctx.request.body;
// do something with value and username
ctx.status = 200;
}
it("With correct gameKey: should return the rating of the game",done => {
chai
.request('http://localhost:3000')
.post('/foo/bar')
.set('content-type','application/json')
.send({value: 3});
.end((err,res) => {
// do some tests
done();
});
});
这是服务器索引和测试文件中的全部代码:
const Koa = require('koa');
const Jwt = require('koa-jwt');
const Router = require('koa-router');
const Cors = require('@koa/cors');
const BodyParser = require('koa-bodyparser');
const Helmet = require('koa-helmet');
const app = new Koa();
const router = new Router();
router.post('/foo/bar',bar);
async function bar(ctx,next) {
const { username } = ctx.state.user;
const { value } = ctx.request.body;
// do something with value and username
ctx.status = 200;
}
app.use(Helmet());
app.use(Cors());
app.use(BodyParser({
enableTypes: ['json'],strict: true,onerror(err,ctx) {
ctx.throw('Request body could not be parsed',422);
},}));
app.use(Jwt({ secret: process.env.SECRET }).unless({
path: [
// Whitelist routes that don't require authentication
/^\/auth/,],}));
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000,() => console.log(`API server started on localhost:3000`));
const chai = require("chai");
const chaiHttp = require("chai-http");
chai.use(chaiHttp);
const expect = require('chai').expect;
const userCredentials = {
username: 'chai',password: 'chai'
}
describe("Route: games/",() => {
before(() => {
chai
.request('http://localhost:3000')
.post('/auth')
.set('content-type','application/json')
.send(userCredentials)
.end((err,res) => {
expect(res.status).to.be.eql(200);
});
});
describe("Sub-route: GET /",() => {
describe("Sub-route: PUT /:gameKey/rating",() => {
it("With correct gameKey: should return the rating of the game",done => {
chai
.request('http://localhost:3000')
.post('/foo/bar')
.set('content-type','application/json')
.send({value: 3});
.end((err,res) => {
expect(res.status).to.be.eql(200);
done();
});
});
});
});
});