[英]How to use Mocha and Unitjs to test a Sails js controller that requires login?
I am new to testing. 我是新手测试。 Recently I have developed one Sails project. 最近我开发了一个Sails项目。 It works fine. 它工作正常。 But now I want to write test cases for the whole project. 但现在我想为整个项目编写测试用例。 I am facing the problem of how to first authenticate and then test the Sails project using Mocha and Unit Js. 我面临的问题是如何首先进行身份验证,然后使用Mocha和Unit Js测试Sails项目。
One of my controllers has a function that displays a report, but only to those users who are logged in. How can I write a test case for this logic? 我的一个控制器有一个显示报告的功能,但仅限于那些登录的用户。如何为这个逻辑编写测试用例?
Thanks 谢谢
Try this, 试试这个,
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();
});
thanks 谢谢
For sails 1.0 , the following works: 对于帆1.0 ,以下工作:
First, make sure you define an own test environment where you disable csrf
. 首先,确保定义一个禁用csrf
的自己的测试环境。
security: {
csrf: false
}
If you do not do this, you will later not be able to authenticate in your tests and receive 403
errors. 如果您不这样做,以后将无法在测试中进行身份验证并收到403
错误。
Optionally (if you do use a ephemeral database for testing like the in-memory-db), create a user in the lifecycle.test.js
file's callback where you find the comment here you can load fixtures, etc.
: (可选)(如果您确实使用临时数据库进行测试,例如内存数据库),请在lifecycle.test.js
文件的回调中创建一个用户,您可以在here you can load fixtures, etc.
找到注释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') },
]);
Then execute your test the following way (using promises): 然后按以下方式执行测试(使用promises):
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;
});
});
});
});
This way, you first authenticate with your test user and then execute your test function with that user. 这样,您首先要与测试用户进行身份验证,然后对该用户执行测试功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.