单元测试中多个 httpRequest() 如何保持cookie?
SuperTest中有agent函数可以模仿浏览器对Cookie的持久化行为,但是 app.httpRequest 似乎并不可以? 两个请求似乎是完全独立的?
以下代码来自SuperTest - Readme
const request = require('supertest');
const should = require('should');
const express = require('express');
const cookieParser = require('cookie-parser');
describe('request.agent(app)', function() {
const app = express();
app.use(cookieParser());
app.get('/', function(req, res) {
res.cookie('cookie', 'hey');
res.send();
});
app.get('/return', function(req, res) {
if (req.cookies.cookie) res.send(req.cookies.cookie);
else res.send(':(')
});
const agent = request.agent(app);
it('should save cookies', function(done) {
agent
.get('/')
.expect('set-cookie', 'cookie=hey; Path=/', done);
});
it('should send cookies', function(done) {
agent
.get('/return')
.expect('hey', done);
});
})
加上下面这句就OK了
app.mockSession({});
@zhennann 加上这句的确可以工作,但是我发现却无法删除Cookie了。 我在测试登陆与登出。加上这句之后确实可以通过login请求登陆了,但是接下来使用logout却无法登出用户。 logout中登出用户的方法是删除该Session:
ctx.session = null;
然而同样的代码,我实际用Postman调用却可以达到预期的效果。 请问有什么解决方案吗? 其实我觉得最直接的能mock一个浏览器就好了……
可以从第一个请求拿到 cookie ,再第二个请求添加这个 cookie
也可以在登出后,调用
mock.restore();
@zhennann 没错,但是这样似乎就没有测试的意义了,因为是我的测试的代码清空了Session,而不是被试的逻辑。 不知道我的理解对不对?
@popomore 是可以这样手动模拟,但是我觉得比较繁琐。 因为SuperTest其实是有一个Agent的支持的,可以支持persist cookie,我在想能否做一个MockAgent出来,实现类似的功能,应该是方便很多了吧?
mock本意就是mock,辅助你达到测试的效果,不必强求真实环境一比一的完全重现
发自我的 iPhone
在 2018年3月18日,下午11:28,AZLisme [email protected] 写道:
@zhennann 没错,但是这样似乎就没有测试的意义了,因为是我的测试的代码清空了Session,而不是被试的逻辑。 不知道我的理解对不对?
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub, or mute the thread.
你可以直接使用 supertest 的 agent
如何构建这样一个agent呢,能否给一个简单的示范? 我使用类似下面的代码会出现错误:
const { app, assert } = require('egg-mock/bootstrap');
const supertest = require('supertest')
...
const agent = supertest.agent(app);
agent.get("/");
会抛出错误TypeError: app.address is not a function
已经解决,我使用
const agent = supertest.agent(app.server);
似乎就可以了
也可以 const agent = supertest.agent(app.callback());
@popomore 咱要支持个 app.httpRequest({ agent }) 么
或者 Test 有没有 .agent() 方法,可以 app.httpRequest().agent(my_agent).get('/')
我觉得可以
@popomore 咱要支持个
app.httpRequest({ agent })么或者 Test 有没有
.agent()方法,可以app.httpRequest().agent(my_agent).get('/')
这个方法很棒啊! 我现在就面临只能传递cookie的问题。如果有一个 agent 能贯穿始终,方便不少!
我觉得可以
Any update?