gpt4 book ai didi

node.js - 如何为用户需要登录的网页编写单元测试

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:19 25 4
gpt4 key购买 nike

我正在为用户只能在登录后访问的页面编写单元测试。我有以下代码来测试用户是否已成功登录:

describe('login', function () {
this.timeout(20000);
it('should login with correct password', function (done) {
this.timeout(20000);
setTimeout(done, 20000);
request.post('/login')
.send({
username:"admin@admin.com",
password:"admin1"
})
.expect('Location','/profile')
.end(done);
});
});

测试有效,然后我尝试添加以下代码:

describe('secret page',function(){
it('should get secret',function(done){
request.get('/secret')
.expect('Location','/secret')
.end(done);
});
});

我希望用户应该能够获取 secret 页面,但我收到错误:

GET /secret 302 0.424 ms - 28
Error: expected "Location" of "/secret", got "/login"
at Test._assertHeader (\node_modules\supertest\lib\test.js:247:12)
at Test._assertFunction (\node_modules\supertest\lib\test.js:281:11)
at Test.assert (\node_modules\supertest\lib\test.js:171:18)
at Server.assert (\node_modules\supertest\lib\test.js:131:12)
at emitCloseNT (net.js:1554:8)
at _combinedTickCallback (internal/process/next_tick.js:77:11)
at process._tickCallback (internal/process/next_tick.js:104:9)

我尝试将第二个“it”函数放入第一个描述 block 中,但出现了相同的错误。但当网站运行时,用户可以正确进入 secret 页面,而不是返回登录页面。

最佳答案

您可以尝试调查授权的工作原理。也许您可以从 header 中获取一些 token 并稍后使用它,只需将正确的 header 附加到您的请求中即可。

另一个选择可能是使用 mocha 的 beforeEach() 钩子(Hook)。

关于node.js - 如何为用户需要登录的网页编写单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44196690/

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