使用 mocha、sinon 和 chai 运行测试时,res.status(...).json 不是一个函数

EI-*_*-01 1 testing mocha.js node.js express chai

您好,我遇到了控制器单元测试失败的情况。我模拟了响应对象,但测试一直失败json is not a function,因为 statusCode 为undefined200,并且测试失败。

exports.getAllPrograms = async (req, res) => {
    try {
        let programs = [];
        const result = await Program.fetchAll();
        result.rows.forEach(item => {
            programs.push(new Program(item.id, item.name, item.description))
        });
        res.status(200).json(programs);
        
    } catch(err) {
        if (!err.statusCode) {
            err.statusCode = 500;
        }
        console.log(err);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的单元测试:

it('', async () => {
     sinon.stub(Program, 'fetchAll')
     Program.fetchAll.returns(Promise.resolve({rows:[{id:1, name:"John", description:"Having a bad day with testing"}]}))
     const res = {
         send: function(){},
         json: (d) => {
            console.log("\n : " + d);;
         },
         status: (s) => {
             this.statusCode = s;
             return this;
         }
     };

     await ProgramController.getAllPrograms({}, res);
     expect(res.statusCode).to.equal(200);
     Program.fetchAll.restore();
 })
Run Code Online (Sandbox Code Playgroud)

尝试运行测试时出现错误消息:

TypeError: res.status(...).json is not a function
    at Object.exports.getAllPrograms (/Users/Documents/scratch/controllers/program.js:10:25)
    at async Context.<anonymous> (/Users/Documents/scratch/test/controller-test.js:21:6) {
  statusCode: 500
}

  0 passing (9ms)
  1 failing

  1) :
     AssertionError: expected undefined to equal 200
      at Context.<anonymous> (test/controller-test.js:23:32)
Run Code Online (Sandbox Code Playgroud)

EI-*_*-01 7

哈哈我想到了问题所在。创建模拟对象时,我应该避免使用箭头函数。基本上用函数表达式替换箭头函数。

const res = {
         send: function(){},
         json: (d) => {
            console.log("\n : " + d);;
         },
         status: (s) => {
             this.statusCode = s;
             return this;
         }
     };
Run Code Online (Sandbox Code Playgroud)

const res = {
         send: function(){},
         json: function(d) {
            console.log("\n : " + d);;
         },
         status: function(s) {
             this.statusCode = s;
             return this;
         }
     };
Run Code Online (Sandbox Code Playgroud)