When using two nested chai requests, session get lost.
chai.request(server)
.post('/api/v1/account/login')
.send({_email: '[email protected]', _password: 'testtest'})
.end(function(err, res){
chai.request(server)
.get('/api/v1/user/me')
.end(function(err2, res2){
//here i should get the session, but its empty
res2.should.have.status(200);
done();
});
});
And i'm pretty sure that it's an error in my mocha test, because i tried it (the login and then retrieving the session) outside the test and the session is being setted.
To install the dependencies, you can fire the following command: Mocha and chai are very famous Unit Testing Frameworks for automated testing. We will be using chai-http module to make HTTP Requests. Create a file test.js in the test folder of your express application folder:
Mocha is a feature-rich JavaScript test framework running on Node and in the browser, and it’s specially convenient for asynchronous testing. We’ll install mocha as a development dependency for our project: Chai is an assertion library that integrates very well with Mocha. Let’s install it:
Mocha allows you to use any assertion library you wish such as should.js, expect.js, chai, better-assert and unexpected. Chai can be paired with any javascript testing framework (for instance Mocha) Chai has several interfaces that allow the developer to choose.
These should be used to set up preconditions and clean up after your tests. Assertions are critical to writing test as they validate whether or not the test passed successfully. Mocha allows you to use any assertion library you wish such as should.js, expect.js, chai, better-assert and unexpected.
express itself does not have any native session support. I guess you are using some session middleware such as https://github.com/expressjs/session.
Meanwhile, I guess you are using chai-http plugin to send HTTP request. In chai-http, in order to retain cookies between different HTTP requests (so that req.session can be available in express side), you need to use chai.request.agent
rather than chai
.
Here is a simple example for your code:
var agent = chai.request.agent(app);
agent.post('/api/v1/account/login')
.send({_email: '[email protected]', _password: 'testtest'})
.then(function(res){
agent.get('/api/v1/user/me')
.then(function(res2){
// should get status 200, which indicates req.session existence.
res2.should.have.status(200);
done();
});
});
For chai.request.agent
, you can refer to http://chaijs.com/plugins/chai-http/#retaining-cookies-with-each-request
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With