gpt4 book ai didi

node.js - Mocha 测试,链接 super 测试请求

转载 作者:太空宇宙 更新时间:2023-11-04 00:46:17 24 4
gpt4 key购买 nike

因此,我尝试在我的 Express 应用程序中测试一条路线,为此,我需要在调用电话之前登录用户。我在 beforeEach 函数中创建并保存一个 user。这是我正在编写的测试:

it('should update username', function(done){
var _this = this;
req.post('/login')
.send(_this.data)
.then(function(res){
req.put('/users/' + res.body.user._id)
.send({ username: 'robert'})
.expect(200)
.end(function(err, res){
if(err) return done(err);
console.log(res.body);
res.body.success.should.equal(true);
res.body.user.username.should.match(/robert/);
done();
});
});
});

这是我运行测试时得到的输出:

  Users
Routes
Authenticated
POST /login 200 195.059 ms - 142
PUT /users/568a432e1daa24083fa6778a 401 2.785 ms - 21
1) should update username
Unauthenticated
GET /users 401 1.502 ms - 21
✓ should return 401


1 passing (516ms)
1 failing

1) Users Routes Authenticated should update username:
Error: expected 200 "OK", got 401 "Unauthorized"
at Test._assertStatus (node_modules/supertest/lib/test.js:232:12)
at Test._assertFunction (node_modules/supertest/lib/test.js:247:11)
at Test.assert (node_modules/supertest/lib/test.js:148:18)
at Server.assert (node_modules/supertest/lib/test.js:127:12)
at net.js:1273:10

我很困惑为什么当 POST/login 请求响应 200 时,它却以 401 响应。

使用Postman我能够创建一个用户,以该用户身份登录,并且通过PUT请求我能够成功更新数据。因此,我假设这与 supertestreq 链接有关。

我已经使用 supertest-as-promised 以及 supertest 编写了请求链。

据我了解,以下代码的行为与使用 then() 语法相同:

it('should update username', function(done){
var _this = this;
req.post('/login')
.send(_this.data)
.endfunction(err, res){
if(err) return done(err);
req.put('/users/' + res.body.user._id)
.send({ username: 'robert'})
.expect(200)
.end(function(err, res){
if(err) return done(err);
console.log(res.body);
res.body.success.should.equal(true);
res.body.user.username.should.match(/robert/);
done();
});
});
});

我对这里发生的事情感到困惑。就像我说的,我可以使用 Postman 来做到这一点,所以我认为这是请求链如何工作的问题。如果您需要更多上下文,我可以根据需要提供更多代码。

最佳答案

解决方案就像更改一样简单

var req = require('supertest-as-promised')(app);

var req = require('supertest-as-promised').agent(app);

调用supertest.agent允许supertest作为网络 session 工作并在链接请求时保留 session 、cookie 和 header 。

关于node.js - Mocha 测试,链接 super 测试请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34589011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com