亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何測試 expressJS 控制器-NodeJS

如何測試 expressJS 控制器-NodeJS

蠱毒傳說 2021-10-29 15:09:45
試圖對我的控制器進行單元測試,但是當我這樣做時,我收到以下錯誤。我愿意用不同的方式來測試我的控制器。錯誤:類型錯誤:預期的 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);      })    );  });
查看完整描述

1 回答

?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

首先,在詢問 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);

    })

  );

});

現在,對于您的問題,這就是您收到錯誤的原因。首先要測試的是:當我更新到最新版本的測試依賴項時,會不會出現這個bug?答案是,不,它不會出現。所以基本上,這是關于你使用sinon-test2.0 版,它與 Sinon 3 有一個兼容性錯誤。這是來自更新日志:


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 

這里的錯誤當然不是真正的錯誤,而只是我沒有完整實現控制器和車輛類的副產品。


查看完整回答
反對 回復 2021-10-29
  • 1 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號