单元测试 Express 控制器

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

已经为此工作好几天了。终于突破并寻求帮助。

当我运行服务器并进行 API 调用时,一切都会按预期进行。

现在我正在尝试对控制器进行单元测试并遇到问题。希望得到一些澄清,因为我显然错过了一些重要的东西。

classCodesController.js(基本最低代码。我已经在我的测试中注释掉了除此之外的所有内容)

import { classCodeModel } from '../models/classCodeModel.js';
import { asyncHandler } from '../utils/asyncHandler.js';

const getAll = async (req, res, next) => {
    const record_set = [];

    res.status(400).json({
        status: 'success',
        length: record_set.length,
        data: record_set
    });
};

export {
    getAll
};

classCodesController.test.js

import assert from 'node:assert/strict';
import { describe, it, mock } from 'node:test';
import mockHttp from 'node-mocks-http';
import { getAll } from '../../src/controllers/classCodeControllerv1.js';
import { classCodeModel } from '../../src/models/classCodeModel.js';

describe('getAll: return JSON', () => {
        it('should return array of two records as JSON', { timeout: 5000 }, async () => {
            const req = mockHttp.createRequest();
            const res = mockHttp.createResponse();
            const next = mock.fn();

            await getAll(req, res, next);

            assert.deepStrictEqual(res.statusCode, 400);
            assert.deepStrictEqual(res.json(body), { status: 'success', length: 0, data: [] });
    });
});

调用时状态码不变,不返回json。

我尝试传递自己的 res 对象,该对象在我对中间件模块进行单元测试时起作用。

            const res = {
                body: '',
                data: {},
                message: undefined,
                statusCode: 100, // noramlly defaults to 200
                statusText: '', // normally 'OK'
                headers: {},
                config: {},
                reqeust: {},
                send: mock.fn(),
                status: mock.fn(c => {
                    this.statusCode = c;
                    return this;
                }),
                json: mock.fn(d => {
                    this.message = d;
                    console.log('json d: ', d);
                })
            }

json函数中的console.log输出了controller提交的数据,但是到了测试时message仍然是未定义的(TypeError: Cannot set properties of undefined (setting 'message')),并且statusCode没有改变。

感谢所有帮助。预先感谢。

javascript node.js express unit-testing es6-modules
1个回答
0
投票

文档中,您应该使用

res._getJSONData()
来获取响应JSON数据。下面是一个工作示例:

getAll.js

const getAll = async (req, res) => {
    const record_set = [];
    res.status(400).json({
        status: 'success',
        length: record_set.length,
        data: record_set,
    });
};

export { getAll };

getAll.test.js

import assert from 'node:assert/strict';
import { describe, it, mock } from 'node:test';
import mockHttp from 'node-mocks-http';
import { getAll } from './getAll.js';

describe('getAll: return JSON', () => {
    it('should return array of two records as JSON', async () => {
        const req = mockHttp.createRequest();
        const res = mockHttp.createResponse();
        const next = mock.fn();

        await getAll(req, res, next);

        assert.deepStrictEqual(res.statusCode, 400);
        assert.deepStrictEqual(res._getJSONData(), { status: 'success', length: 0, data: [] });
    });
});

测试结果:

$ node --test ./getAll.test.js
▶ getAll: return JSON
  ✔ should return array of two records as JSON (1.215ms)
▶ getAll: return JSON (2.3065ms)

ℹ tests 1
ℹ suites 1
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 80.1445

package.json

{
  "name": "77646756",
  "version": "1.0.0",
  "type": "module",
  "devDependencies": {
    "node-mocks-http": "^1.14.0"
  }
}

节点版本:

$ nvm ls

  * 21.4.0 (Currently using 64-bit executable)
    18.19.0
    16.20.2
© www.soinside.com 2019 - 2024. All rights reserved.