I use nestjs and use jest test api. I use transactions rollback data when save database error.
My function look like :
Some code
await this.dataSource.manager.transaction(async (manager) => {
await Promise.all(
input.map(async (it) => {
//some logic handle (check data,some thing)
Unit test
describe('someTest', () => {
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
ExampleService,
{
provide: exampleRepository,
useValue: {
save: jest.fn(),
find: jest.fn(),
softDelete: jest.fn(),
},
},
{
provide: DataSource,
useFactory: dataSourceMockFactory,
},
],
}).compile();
service = module.get<SomeService>(SomeService);
repo = module.get<SomeRepository>(SomeRepository);
});
it('should successfully when insert db', async () => {
const service = jest.spyOn(service, 'functionTest');
await service.functionTest(
'123',
someinput,
);
expect(service).toHaveBeenCalledWith(
'123',
someinput,
);
});
Class: dataSourceMockFactory
export const dataSourceMockFactory: () => MockType<DataSource> = jest.fn(() => ({
connect: jest.fn(),
transaction: jest.fn(),
release: jest.fn(),
rollbackTransaction: jest.fn(),
manager: {
transaction: jest.fn().mockImplementation(() => ({
create: jest.fn(),
})),
save: jest.fn(),
},
}));
export type MockType<T> = {
[P in keyof T]?: jest.Mock<{}>;
};
But when i running test, test case only running await this.dataSource.manager.transaction(async (manager) => { and skip await Promise.all( or any input.map(async (it) => {. It return success and not check All function inside promies and input map. I don't know why. How to test any code in promies.all inside transactions.