I'm testing my API with supertest
I want to check that my CSRF token protection works, and then disable it for the other tests.
For this I set NODE_ENV
to test
or not_test
app.js
var csrf = require('csurf');
var app = express();
if (process.env.NODE_ENV !== 'test') {
app.use(csrf({ cookie: true }));
app.use(function(req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
return next();
});
}
Test CSRF
process.env.NODE_ENV = 'not_test';
var app = require("app.js");
var request = require('supertest')(app);
var testAccount = {
"login": "test",
"pass": "test"
};
describe('CSRF protection', function() {
it('On /login', function(done){
request
.post('/login')
.send(testAccount)
.expect(403, done);
});
});
Test login NODE_ENV is now test
process.env.NODE_ENV = 'test';
var app = require("app.js");
var request = require('supertest').agent(app);
var testAccount = {
"login": "test",
"pass": "test"
};
describe('API Admin roads', function() {
before(function (done) {
request
.post('/login')
.send(testAccount)
.end(done);
});
it('/api/admin/groups/', function(done){
request
.get('/api/admin/groups/')
.expect(200, done);
});
});
The problem is, only the first process.env.NODE_ENV
is taken into account, if I set it to not_test
and then to test
I will still be in not_test
mode.
process.env.NODE_ENV
need to be set beforeapp.js
is included as the testNODE_ENV !== 'test'
is done inapp.js
– Mchaleconsole.log("ENV : " + process.env.NODE_ENV);
in app.js only display one line (although there is 2 tests from 2 differents files run). I guess therequire('app.js');
is kept in cache – Mchaledelete require.cache[require.resolve("app.js")]
makes it work !!! – Mchale