So, I am trying to write some unit tests for my code using MochaJS, SinonJS, rewire, chai and assert. An i got the following error:
1) async function addOneRoom(db, newRoom)
should reject error when the maximum room number has been reached:
AssertionError [ERR_ASSERTION]: Missing expected rejection (Error).
at async Context.<anonymous> (test\test.js:33:9).
So the function I am testing is the following one:
async function addOneRoom(db, newRoom) {
const roomNumber = await createRoomNumber(db, newRoom.floor);
if (roomNumber !== 0) {
newRoom.roomNumber = roomNumber;
const result = await db.rooms.insertOne(newRoom);
return newRoom
} else return new Error("No room can be added on this floor. The maximum numar of rooms has been reached")}
And my unit test for it is:
describe("async function addOneRoom(db, newRoom)", () => {
const addOneRoom = rewired.__get__("addOneRoom")
const sandBox = sinon.createSandbox()
it("should reject error when the maximum room number has been reached", async () => {
const newRoom = {
floor: 1,
sqm: 20,
capacity: 5,
features: {
videoProjector: 1,
stage: 2
}
}
const insertOne = sandBox.stub().returns()
const mockedCreateRoomNumber = sandBox.stub().resolves(0)
const db = {
rooms: { insertOne }
}
const stubbedRoomNumber = rewired.__set__({ createRoomNumber: mockedCreateRoomNumber })
await assert.rejects(addOneRoom(db, newRoom), new Error("No room can be added on this floor. The maximum numar of rooms has been reached"))
// sandBox.assert.calledOnceWithExactly(stubbedRoomNumber)
sandBox.assert.calledOnceWithExactly(insertOne, {newRoom})
const order = [
// stubbedRoomNumber,
insertOne
]
sandBox.assert.callOrder(...order)
stubbedRoomNumber()
})
I would appreciate any help!
Don't return the Error, throw it:
throw new Error("No room can be added on this floor. The maximum numar of rooms has been reached")}
Returning an Error is no different from returning anything else, and will not cause a promise rejection.