Skip to content

Instantly share code, notes, and snippets.

@m3kh66
Created March 12, 2016 20:16
Show Gist options
  • Save m3kh66/d2da56b3630ac185db9b to your computer and use it in GitHub Desktop.
Save m3kh66/d2da56b3630ac185db9b to your computer and use it in GitHub Desktop.
How to test a request protected with express.js csurf and supertest?
'use strict';
var request = require('supertest');
var jsdom = require('jsdom');
var app = require('../../app');
describe('account middleware', () => {
var server;
before(() => {
// initializing server
server = app({
port: (process.env.PORT || 5000),
});
});
after(() => {
server.close();
});
describe('#POST /signup', () => {
let token;
let cookies;
beforeEach((done) => {
request(server)
.get('/signup')
.end((er, resp) => {
// getting cookies
cookies = resp.headers['set-cookie'];
// extracting token
jsdom.env(resp.text, (err, window) => {
token = window.document.getElementsByName('_csrf')[0].value;
done();
});
});
});
it('should sign up a new user', (done) => {
// act & assert
request(server)
.post('/signup')
.type('form')
.set('Cookie', cookies)
.send({
_csrf: token,
email: '[email protected]',
username: 'admin',
password: '123'
})
.expect(200, done);
});
});
});
'use strict';
var express = require('express');
var csrf = require('csurf');
module.exports = function(options) {
var router = express.Router();
router.use(csrf({ cookie: true }));
// /signup
router
.route('/signup')
.get(function(req, res) {
res.render('signup', { csrfToken: req.csrfToken() });
// ...
})
.post(function(req, res) {
res.render('signup', { csrfToken: req.csrfToken() });
// ...
});
return router;
};
@hilleer
Copy link

hilleer commented Apr 27, 2022

Thank you for this gist. It lead me to a solution for a very similar issue!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment