我如何在测试(玩笑)中手动设置变量的值?

问题描述 投票:0回答:1

app.test.js


我的笑话文件中包含以下代码:

'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上查看了类似的问题,但找不到更具体的答案)。

app.js


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).

    ...

});
javascript node.js express jestjs supertest
1个回答
0
投票

您可以使用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
© www.soinside.com 2019 - 2024. All rights reserved.