[英]Service Layer Unit testing with Sinon.js - Error “x” is not a constructor
我遵循了中等指南: https://medium.com/@tehvicke/integration-and-unit-testing-with-jest-in-nodejs-and-mongoose-bd41c61c9fbc試圖開發一個測試套件。 我的代碼和他的一模一樣,但我遇到了TypeError: Tournament is not a constructor
我放了一些代碼,所以你可以看到我想要做什么。
TournamentService.js
const createTournament = (Tournament) => (tournamentObj) => {
const {name, creator} = tournamentObj;
const newTournament = new Tournament({name, creator});
return newTournament.save();
};
TournamentService.test.js
const TournamentService = require("../TournamentService");
const sinon = require("sinon");
describe("create Tournament test", () => {
it("creates a tournament", () => {
const save = sinon.spy();
console.log("save ", save);
let name;
let creator;
const MockTournamentModel = (tournamentObject) => {
name = tournamentObject.name;
creator = tournamentObject.creator;
return {
...tournamentObject,
save,
};
};
const tournamentService = TournamentService(MockTournamentModel);
const fintoElemento = {
name: "Test tournament",
creator: "jest",
};
tournamentService.createTournament(fintoElemento);
const expected = true;
const actual = save.calledOnce;
expect(actual).toEqual(expected);
expect(name).toEqual("Test tournament");
});
});
我發現了錯誤,問題是我試圖用箭頭 function 創建 MockTournamentModel,而不是你應該使用經典的 function(或一些 ZEFE90A8E604A7C840E88D03 重新編譯成 a76640E88D03 的經典函數)
關鍵字new做了一些事情:
它創建一個新的 object。 這個 object 的類型就是 object。
- 它將這個新對象的內部、不可訪問的 [[prototype]](即 __proto__)屬性設置為構造函數的外部、可訪問的原型 object(每個 function ZA8CFDE6331BD4B62AC96F891 自動具有一個原型。)
箭頭 function沒有這個,arguments 或其他特殊名稱完全綁定。
這就是為什么它不適用於箭頭 function .. 希望這能幫助其他人避免我的錯誤!
https://zeekat.nl/articles/constructors-considered-mildly-confusing.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.