Created
March 12, 2016 20:16
-
-
Save m3kh66/d2da56b3630ac185db9b to your computer and use it in GitHub Desktop.
How to test a request protected with express.js csurf and supertest?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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); | |
}); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this gist. It lead me to a solution for a very similar issue!