所以我正在使用 MochaJS、SinonJS、Chai、assert 和 rewire 对我的应用程序进行单元测试。我收到以下错误。我正在尝试测试作为 POST 方法中的参数传递的 POST 方法的处理程序。我不认为我正确地存根和模拟。
TypeError: roomsRepo.addOneRoom is not a function
at D:\Work\RestAPI\controllers\roomsController.js:10:29
at async Context.<anonymous> (test\testRoomController.js:106:24)
我正在测试的代码是这个:
function createRoomHandler (db) {
return async (request, reply) => {
try {
let newRoom = await request.body;
await roomsRepo.addOneRoom(db, newRoom);
return newRoom
} catch (error) { throw error }
};
}
在 post 方法中作为参数传递的函数:
fastify.post('/rooms', roomOpts.addRoomOpts, createRoomHandler(db));
我的单元测试代码如下:
describe("POST /rooms request handler unit tests", () => {
const createRoomHandler = rewired.__get__("createRoomHandler")
const sandbox = sinon.createSandbox();
it("should delete a room and return its number", async () => {
const req = {
res: {
"statusCode": 200,
"headers": {
"content-type": "application/json"
}
},
body: {
"status": "success",
data: {
"floor": 1,
"sqm": 20,
"capacity": 5,
"features": {
"videoProjector": 1,
"stage": 2
}
}
}
}
const res = {
"data": {
"floor": 1,
"sqm": 20,
"capacity": 5,
"features": {
"videoProjector": 1,
"stage": 2
}
}
}
const insertOne = sandbox.stub().returns()
const db = {
rooms: { insertOne }
}
const mockedAddOneRoom = sandbox.stub().resolves()
const roomsRepo = {mockedAddOneRoom}
const stubbedAddOneRoom = rewired.__set__({ roomsRepo: roomsRepo })
const handler = createRoomHandler(db);
const result = await handler(req.body.data, res);
sandbox.assert.calledOnceWithExactly(mockedAddOneRoom, db, req.body.data)
const order = [
mockedAddOneRoom
]
sandbox.assert.callOrder(...order)
expect(result).be.equal(res.data)
stubbedAddOneRoom()
})
})