Typescript 如何为mongo db模型方法重置jest模拟
下面是存储库函数Typescript 如何为mongo db模型方法重置jest模拟,typescript,unit-testing,mongoose,jestjs,mocking,Typescript,Unit Testing,Mongoose,Jestjs,Mocking,下面是存储库函数 const documentToObject = (document: CustomerDocument): ICustomerModel => { return document.toObject({ getters: true }) as ICustomerModel; }; const createCustomer = async ( customer: ICustomerModel ): Promise< ICustomerModel > =&g
const documentToObject = (document: CustomerDocument): ICustomerModel => {
return document.toObject({ getters: true }) as ICustomerModel;
};
const createCustomer = async (
customer: ICustomerModel
): Promise< ICustomerModel > => {
try {
const customerDocument = await CustomerModel.create(customer);
return documentToObject(customerDocument);
} catch (error) {
logger.error('Error while saving customer');
throw new AppError(ERROR_CODE.FAILED_TO_CREATE_CUSTOMER);
}
};
在这个错误单元案例之后,如果我对任何其他测试案例使用CustomerRepository.createCustomer,它也会抛出。jest不是在每次测试后清除模拟。我如何解决这个问题
jest.mock('mongoose', () => {
const mongoose = require.requireActual('mongoose');
return new mongoose.Mongoose();
});
describe('customer repository', () => {
let mongod: MongoMemoryServer;
beforeAll(async () => {
mongod = new MongoMemoryServer();
const mongoDbUri = await mongod.getConnectionString();
await mongoose.connect(mongoDbUri, { useNewUrlParser: true });
});
beforeEach(() => {
jest.resetAllMocks();
});
afterEach(async () => {
expect.hasAssertions();
await CustomerModel.remove({});
jest.clearAllMocks();
});
afterAll(async () => {
await mongoose.disconnect();
await mongod.stop();
});
describe('#create customer', () => {
it('should create a customer', async () => {
const customer = getCustomer();
const createdCustomer = await customerRepository.createCustomer(customer);
expect(createdCustomer.id).toBeDefined();
});
it('should throw FAILED_TO_CREATE_CUSTOMER when error while creating customer', async () => {
//given
const customer = getCustomer();
CustomerModel.create = jest
.fn()
.mockRejectedValueOnce(new Error('error'));
await expect(
customerRepository.createCustomer(
customer,
)
).rejects.toThrow(ERROR_CODE.FAILED_TO_CREATE_CUSTOMER);
});
});
});