[英]How do I manually set the value of a variable in a test (jest)?
我的笑話文件中有以下代碼:
'use strict';
const request = require('supertest');
const app = require('./app');
//https://stackoverflow.com/questions/1714786/query-string-encoding-of-a-javascript-object
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);
});
});
到目前為止測試很好,但我想在這個特定測試期間設置一個名為Identifier
的變量(在我的 node.js 文件中)等於值1
。 我怎么能通過開玩笑來做到這一點? (我嘗試閱讀文檔以開玩笑,並查看了關於 SO 的類似問題,但無法找到更具體的答案)。
node.js /example POST 路由:
app.post('/example', (req, res) => {
var checked = req.body.check;
var Identifier = req.app.get('identifier'); // Accessed like a global variable (value set in previous block of code).
...
});
您可以使用app.set(name, value)來執行此操作。 例如
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.