Вы можете использовать app.set (имя, значение) , чтобы сделать это. Например,
app.js
:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/example', (req, res) => {
const checked = req.body.check;
const Identifier = req.app.get('identifier');
console.log('Identifier:', Identifier);
res.sendStatus(200);
});
module.exports = app;
app.test.js
:
const request = require('supertest');
const app = require('./app');
function serialise(obj) {
return Object.keys(obj)
.map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`)
.join('&');
}
describe('Test other /', () => {
test('POST /example succeeds (200 OK) if checkboxes are ticked', () => {
const toSend = {
check: 'Spiderman',
};
return request(app).post('/example').send(serialise(toSend)).expect(200);
});
test('POST /example succeeds (200 OK) if Identifier is set', () => {
const toSend = {
check: 'Spiderman',
};
app.set('identifier', 1);
return request(app).post('/example').send(serialise(toSend)).expect(200);
});
});
Результаты интеграционных испытаний:
PASS stackoverflow/61373586/app.test.js (12.805s)
Test other /
✓ POST /example succeeds (200 OK) if checkboxes are ticked (159ms)
✓ POST /example succeeds (200 OK) if Identifier is set (9ms)
console.log stackoverflow/61373586/app.js:9
Identifier: undefined
console.log stackoverflow/61373586/app.js:9
Identifier: 1
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 14.642s