Mocha tested the post route and passed _csrf, but the terminal reported an error CSRF mismatch

  node.js, question

I recently practiced writing tests. When testing a post route, I need to pass CSRF, so I referred to an answer on stackoverflow.
How to test express form post with CSRF?

Referring to this answer, I wrote the following code

var request = require('supertest');
 var should = require('should');
 var app = require('../app');
 var $ = require('jquery')(require("jsdom").jsdom().parentWindow);
 
 
 describe('User', function () {
 
 it('should create a admin', function (done) {
 request(app)
 .get('/rear')
 .expect(200)
 .end(function (err, res) {
 if (err) return done(err);
 should.not.exist(err);
 var $html = $(res.text);
 var csrf = $html.find('input[name=_csrf]').val();
 console.log(csrf);
 should.exist(csrf);
 request(app)
 .post('/user/signup')
 .send({
 _csrf: csrf,
 name: 'admin',
 mobile: '12345678901',
 password: '123456',
 repassword: '123456',
 gender: '0'
 })
 .expect(302)
 .end(function (err, res) {
 if (err) return done(err);
 should.not.exist(err);
 res.header.location.should.include('/rear');
 done();
 });
 });
 });
 });

But the terminal reported an error
Error: CSRF token mismatch
Error: expected 302 “Found”, got 403 “Forbidden”

I don’t know how to deal with this problem. According to my thinking, my test imitates the user’s behavior. First I get csrf in the page of the route /rear, then I post to the route/USER/SIGUP. I don’t know what went wrong.

I found the cause of the problem. although I caught csrf from the back-end expose to the front-end input(name=’_csrf’), I neglected one point, that is, request and cookies should be persisted in the test environment. later I went to see the documents of the next supertest, which has a. agent method that can persist a request and its cookies.

var agent = request.agent(app);

agent

.post('/user/signup')
 .send({
 _csrf: csrf,
 name: 'admin',
 mobile: '12345678901',
 password: '123456',
 repassword: '123456',
 gender: '0'
 })
 
 So the test passed