【问题标题】:how to test expressJS controller- NodeJS如何测试 expressJS 控制器-NodeJS
【发布时间】:2020-01-26 04:58:18
【问题描述】:

尝试对我的控制器进行单元测试,但这样做时出现以下错误。

我乐于接受以不同方式测试我的控制器的答案。

错误:

TypeError: 预期的 sinon 对象

 const test = require('sinon-test');



 describe('index (get all)', function() {
    beforeEach(function() {
      res = {
        json: sinon.spy(),
        status: sinon.stub().returns({ end: sinon.spy() })
      };
      expectedResult = [{}, {}, {}];
    });
    it(
      'should return array of vehicles or empty array',
      test(() => {
        this.stub(Vehicle, 'find').yields(null, expectedResult);
        Controller.index(req, res);
        sinon.assert.calledWith(Vehicle.find, {});
        sinon.assert.calledWith(res.json, sinon.match.array);
      })
    );
  });

【问题讨论】:

    标签: javascript node.js express sinon chai


    【解决方案1】:

    首先,在询问 StackOverflow 问题时,发布一个完全可运行的示例并说明所有依赖项是有意义的。基本上,我用了一个多小时来测试这个,因为两者都丢失了。

    这是一个完全扩展的例子,只是你的两个主要对象的虚拟实现。

    var sinon = require("sinon");
    var sinonTest = require("sinon-test");
    var test = sinonTest(sinon);
    
    const Vehicle = {
      find() {}
    };
    const Controller = {
      index() {}
    };
    
    describe("index (get all)", function() {
      let expectedResult, res, req;
    
      beforeEach(function() {
        res = {
          json: sinon.spy(),
          status: sinon.stub().returns({ end: sinon.spy() })
        };
        expectedResult = [{}, {}, {}];
      });
    
      it(
        "should return array of vehicles or empty array",
        test(function() {
          this.stub(Vehicle, "find").yields(null, expectedResult);
          Controller.index(req, res);
          sinon.assert.calledWith(Vehicle.find, {});
          sinon.assert.calledWith(res.json, sinon.match.array);
        })
      );
    });
    

    现在,对于您的问题,这就是您遇到错误的原因。首先要测试的是:当我更新到测试的依赖项的最新版本时,是否会出现错误?答案是,不,它没有出现。所以基本上,这是关于你使用sinon-test 2.0 版,它与Sinon 3 存在兼容性错误。这是来自changelog

    2.1.0 / 2017-08-07
    ==================
    Fix compatibility with Sinon 3 (#77)
    
    
    2.0.0 / 2017-06-22
    ==================
    
      * Simplify configuration API (#74)
    

    因此,鉴于已经修复,并且正在使用下面的示例,测试完全可以运行:

    mocha mytest.js 
    
    
      index (get all)
        1) should return array of vehicles or empty array
    
    
      0 passing (6ms)
      1 failing
    
      1) index (get all)
           should return array of vehicles or empty array:
         AssertError: expected find to be called with arguments 
    

    这里的错误当然不是真正的错误,而只是我没有完全实现您的控制器和车辆类的副产品。

    【讨论】:

      猜你喜欢
      • 2014-10-04
      • 2019-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      相关资源
      最近更新 更多