You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express控制器单元测试异常求助:状态码与JSON返回问题

解决Express控制器单元测试的两个问题

问题1:node-mocks-http测试中状态码和响应体验证失败

你当前用node-mocks-http的测试代码里,res.json(body)的写法是错误的——res.json()是Express用来发送JSON响应的方法,不是获取响应内容的接口。node-mocks-http提供了_getJSONData()方法来获取已发送的JSON响应体,同时statusCode可以直接从res对象读取。

修改后的测试代码:

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);
            // 获取响应的JSON数据
            const responseBody = res._getJSONData();
            // 验证响应体结构
            assert.deepStrictEqual(responseBody, { 
                status: 'success', 
                length: 0, 
                data: [] 
            });
    });
});

问题2:自定义res对象中this指向错误

你自定义的res对象里,status和json用了箭头函数,箭头函数没有自己的this,它的this继承自外层作用域(这里是测试函数的上下文,不是res对象本身),所以会出现Cannot set properties of undefined的错误。

把箭头函数改成普通函数即可,这样this会绑定到res对象:

const res = {
    body: '',
    data: {},
    message: undefined,
    statusCode: 100, // normally defaults to 200
    statusText: '', // normally 'OK'
    headers: {},
    config: {},
    request: {},
    send: mock.fn(),
    // 改用普通函数
    status: mock.fn(function(c) {
        this.statusCode = c;
        return this;
    }),
    // 改用普通函数
    json: mock.fn(function(d) {
        this.message = d;
        console.log('json d: ', d);
    })
}

内容的提问来源于stack exchange,提问作者nuke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 09:18:37