我已经按照介质指南。https:/medium.com@tehvickeintegration-and-unit-testing-with-jest-in-nodejs-and-mongoos-bd41c61c9fbc。 试图开发一个测试套件。我的代码和他的代码一模一样,但是我遇到了 类型错误。锦标赛不是一个构造函数
我放了一些代码,所以你可以看到我正在尝试做什么。
TournamentService.js
const createTournament = (Tournament) => (tournamentObj) => {
const {name, creator} = tournamentObj;
const newTournament = new Tournament({name, creator});
return newTournament.save();
};
TournamentService.test.js,我按照medium的指导:https:/medium.com@tehvickeintegration-and-unity-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");
});
});
我已经找到了错误,问题是我试图用一个箭头函数来创建MockTournamentModel,而不是你应该使用一个经典函数(或一些重新编译成经典函数的包)。
关键字 新的 做了几件事。
它创建了一个新的对象。这个对象的类型是简单的对象。
- 它设置这个新对象的内部的、不可访问的、[[prototype]] 。(即__proto__)属性作为构造函数的外部的、可访问的、原型对象(每个函数对象都自动有一个原型属性)。
箭头函数 没有 this,参数或其他特殊名称根本没有绑定。
这就是为什么用箭头函数不能用的原因......希望这能帮助别人避免我的错误!
https:/zeekat.nlarticlesconstructors-considered-mildly-confusing.html。