使用 Mocha 和 Chai 在 Nodejs 中对控制器功能进行单元测试

Unit testing controller functions in Nodejs using Mocha and Chai

我的控制器中有一个函数,它接受 2 个参数请求和响应。

function convertTime (req, res) {
   callOtherFunction().then(function(result){
       res.status(200).send(result);
    }
}

我用来测试这个函数的单元测试函数看起来像这样。

describe('Testing my function ', function() {
  var req = {
      query: {}
     };

 var res = {
     sendCalledWith: '',
     send: function(arg) { 
              this.sendCalledWith = arg;
            },
    json: function(err){
            console.log("\n : " + err);
            },
     status: function(s) {this.statusCode = s; return this;}
   };

  it('Should error out if no inputTime was provided', function() {
    convertTime(req,res);
    expect(res.statusCode).to.equal(500)
  });

});

当我 运行 我的单元测试时,它没有等待我的响应来解决。由于我这里没有等待的回调函数,如何让测试等待 res 对象更新?

它更喜欢 return 来自使用它们的函数的承诺。这自然是在 async 函数中完成的。即使这在生产中不需要,这也提高了可测试性。

function convertTime (req, res) {
   return callOtherFunction().then(function(result){
       res.status(200).send(result);
    }

然后可以链接一个 promise:

  it('Should error out if no inputTime was provided', async function() {
    await convertTime(req,res);
    expect(res.statusCode).to.equal(500)
  });