我是新手测试。最近我开发了一个Sails项目。它工作正常。但现在我想为整个项目编写测试用例。我面临的问题是如何首先进行身份验证,然后使用Mocha和Unit Js测试Sails项目。
我的一个控制器有一个显示报告的功能,但仅限于那些登录的用户。如何为此逻辑编写测试用例?
由于
答案 0 :(得分:2)
试试这个,
var request=require('supertest');
var cookie;
request(app)
.post('/login')
.send({ email: "user@gluck.com", password:'password' })
.end(function(err,res){
res.should.have.status(200);
cookie = res.headers['set-cookie'];
done();
});
//
// and use the cookie on the next request
request(app)
.get('/v1/your/path')
.set('cookie', cookie)
.end(function(err,res){
res.should.have.status(200);
done();
});
感谢
答案 1 :(得分:1)
在测试环境中,您可以使用Cookie来保存会话信息。您可以通过Sails,Mocha和supertest检查我的GIST cookie使用示例: gist
答案 2 :(得分:0)
对于 sails 1.0 ,以下工作有效:
首先,请确保定义一个自己的测试环境,以在其中禁用csrf
。
security: {
csrf: false
}
如果不这样做,以后将无法在测试中进行身份验证并收到403
错误。
(可选)(如果您确实使用了临时数据库进行测试,例如in-memory-db),请在lifecycle.test.js
文件的回调中创建一个用户,在其中找到注释here you can load fixtures, etc.
:
await User.createEach([
{ id: 123123, emailAddress: 'tester@myapp.com', fullName: 'Tester 1', isSuperAdmin: true, password: await sails.helpers.passwords.hashPassword('abc123') },
]);
然后以以下方式(使用promise)执行测试:
var supertest = require('supertest');
const login = { emailAddress: 'tester@myapp.com', password: 'abc123' };
describe('This is my test', () => {
describe('#sampleTest()', () => {
it('should perform my action without error', () => {
var cookie;
return supertest(sails.hooks.http.app)
.put('/api/v1/entrance/login')
.send(login)
.expect(200)
.then(response => {
cookie = response.headers['set-cookie'];
// Here comes what you really want to test
return supertest(sails.hooks.http.app)
.put('/api/v1/mycontroller/action/123')
.set('cookie', cookie)
.send()
.expect(200);
}).catch(err => {
console.log(err);
throw err;
});
});
});
});
这样,您首先要与测试用户进行身份验证,然后与该用户一起执行测试功能。