首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >http:无法设置节点ctx.state的值

http:无法设置节点ctx.state的值
EN

Stack Overflow用户
提问于 2019-12-12 10:23:51
回答 2查看 585关注 0票数 0

我正在用NodeJS和KOA创建一个API。在测试中,我使用chai (Chai)和mocha。当我在控制器中使用const { username } = ctx.state.user获取发送请求的用户的用户名时,就会出现问题。当使用我的应用程序(使用Flutter)或使用Postman访问它们时,它可以工作,但是在使用mocha运行测试时,我会得到错误的TypeError: Cannot destructure property 'username' of 'undefined' or 'null'。在调试代码时,我发现ctx有一个用于state的键,但该键的值为空。我尝试了.set(...).send(...)方法,但它们只修改了ctx.request.headerctx.request.body中的值。

因此,我的问题是:是否有可能用chai为ctx.state设置一个值,如果可能,如何设置?我想放一些类似{user: {username: 'chai'}}的东西。

以下是两个主要部分,需要测试的控制器部分和测试方法:

代码语言:javascript
复制
async function bar(ctx, next) {
    const { username } = ctx.state.user;
    const { value } = ctx.request.body;

    // do something with value and username

    ctx.status = 200;
}
代码语言:javascript
复制
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();
        });
});

下面是服务器索引和测试文件的全部代码:

代码语言:javascript
复制
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`));
代码语言:javascript
复制
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();
                    });
            });
        });
    });
});
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-12-12 12:43:19

多亏了Sandeep Patel的评论,我才明白了这一点。我必须使用中间件,所以我在before()方法中保存了与请求一起撤回的令牌,并使用.set("Authorization", "Bearer " + token)将其添加到其他请求中。

然后,工作测试看起来如下:

代码语言:javascript
复制
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/", () => {
    var token;
    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);
                token = res.body.token;  // Added this
            });
    });

    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("Authorization", "Bearer " + token)  // Added this
                    .set('content-type', 'application/json')
                    .send({value: 3});
                    .end((err, res) => {
                        expect(res.status).to.be.eql(200);
                        done();
                    });
            });
        });
    });
});
票数 0
EN

Stack Overflow用户

发布于 2019-12-12 10:40:28

根据KOA文档,ctx.state是通过中间件和您的前端视图传递信息的推荐名称空间。

代码语言:javascript
复制
app.use(function * (next) {
  var ctx = this

  ctx.request
  ctx.response

  ctx.body = 'hello'

  ctx.state.user = yield User.find(id).fetch()
  next()
}

因此,我认为您可以在中间件函数中设置ctx.state,您可以在下一个请求处理程序中使用它。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59302421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档