I have followed the medium guide : https://medium.com/@tehvicke/integration-and-unit-testing-with-jest-in-nodejs-and-mongoose-bd41c61c9fbc trying to develop a test suite. My code is exactly like his but I am having the TypeError: Tournament is not a constructor
I put some code, so you can see what I am trying to do.
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");
});
});
I've found the error, the problem was that I was trying to create the MockTournamentModel with an arrow function, instead you should use a classic function (or some package that re-compile into a classic function)
the keyword new does a few things:
It creates a new object. The type of this object is simply object.
- It sets this new object's internal, inaccessible, [[prototype]] (i.e. __proto__) property to be the constructor function's external, accessible, prototype object (every function object automatically has a prototype property).
The arrow function do not have this, arguments or other special names bound at all.
That's why it did not work with an arrow function.. hope this will help someone else avoid my mistake!
https://zeekat.nl/articles/constructors-considered-mildly-confusing.html