Mongodb Jest mock mongoose.startSession()抛出错误
我在post方法中实现了事务。工作很好。但现在我必须为该方法更新单元测试用例。我试图模拟Mongodb Jest mock mongoose.startSession()抛出错误,mongodb,unit-testing,mongoose,jestjs,Mongodb,Unit Testing,Mongoose,Jestjs,我在post方法中实现了事务。工作很好。但现在我必须为该方法更新单元测试用例。我试图模拟startSession()和startTransaction()来检查是否已被调用。但在运行测试用例时,我发现类似于MongooseError:调用startSession`时连接0断开。我是新手,所以我不知道怎么嘲笑它 方法: static post = (funcCall: Promise<Document>) => async (response: Response, field
startSession()
和startTransaction()
来检查是否已被调用
。但在运行测试用例时,我发现类似于MongooseError:调用
startSession`时连接0断开。我是新手,所以我不知道怎么嘲笑它
方法:
static post = (funcCall: Promise<Document>) => async (response: Response, fields?: string[]) => {
const session = await startSession();
session.startTransaction();
try {
const dbResponse = await funcCall; // model.save(request.body)
// commit the changes if everything was successful
await session.commitTransaction();
success(pick(dbResponse, fields ? fields : ['_id']), 201)(response);
} catch (error) {
// this will rollback any changes made in the database
await session.abortTransaction();
throwError(error);
} finally {
// ending the session
session.endSession();
}
};
it('should perform post when valid parameters is passed.', async () => {
// Preparing
const mockSaveReturn = {
_id: objectID,
test_name: 'sample',
};
jest.spyOn(mongoose, 'startSession')
const spySave = jest.spyOn(modelPrototype.prototype, 'save').mockReturnValueOnce(mockSaveReturn);
const document = new modelPrototype(mockSaveReturn);
// Executing
await post(document.save())(response as Response);
expect(response.send).toHaveBeenCalledWith({ _id: '54759eb3c090d83494e2d804' });
expect(spySave).toHaveBeenCalled();
// Cleaning
spySave.mockClear();
});