0

I'm doing test for my searchService and I realize that the bulk method used to insert data to elasticSearch db has some intern operation.

beforeEach(async () => {
const moduleRef: TestingModule = await Test.createTestingModule({
  providers: [
    SearchService,
    {
      provide: ElasticsearchService,
      useValue: {
        bulk: jest.fn(),
        count: jest.fn(),
        helpers: {
          scrollSearch: jest.fn(),
        },
        search: jest.fn(),
      },
    },
    {
      provide: PrismaService,
      useValue: {
        skus: {
          findMany: jest.fn().mockResolvedValueOnce(findManyMock),
          findUnique: jest.fn().mockResolvedValue({}),
          update: jest.fn().mockResolvedValue({}),
          create: jest.fn().mockResolvedValue({}),
          delete: jest.fn().mockResolvedValue({}),
        },
      },
    },
  ],
}).compile();

the bulk method called:

for await (const chunk of arrayOfBulkBodiesInChunks) {
  const bulkBody = chunk.flatMap((doc) => [
    { index: { _index: this.index } },
    doc,
  ]);

  await this.elasticsearchService.bulk({
    refresh: true,
    body: bulkBody,
  });
}

I'm asking help to write a mock for bulk operations.

Edward
  • 5,942
  • 4
  • 38
  • 55

1 Answers1

0

Hi, you can mock your dependencies or providers, try this:

  • In the same file directory /ElasticsearchService is located, create a file called mocks , example: ElasticsearchService is localted in /service/ElasticsearchService.ts, create a file /service/mocks/ElasticsearchService.ts
  • The mocking ElasticsearchService.ts its going to export the service to mock

    export const ElasticsearchService = jest.fn().mockReturnValue({
     //Name here the function to mock
     bulk: jest.fn().mockReturnValue({
    bulk: jest.fn(),
    count: jest.fn(),
    helpers: {
      scrollSearch: jest.fn(),
    },
    search: jest.fn(),
  })

Then in the beggining of your test.

jest.mock('/file/ElasticsearchService') //Type here the exact ubication of your ElasticsearchService, jest automatically will implement the file with the same name in the folder __mocks__

```beforeEach(async () => {
const moduleRef: TestingModule = await Test.createTestingModule({
  providers: [
    SearchService,
    {
      provide: ElasticsearchService,
      useValue: {
        bulk: jest.fn(),
        count: jest.fn(),
        helpers: {
          scrollSearch: jest.fn(),
        },
        search: jest.fn(),
      },
    },
    {
      provide: PrismaService,
      useValue: {
        skus: {
          findMany: jest.fn().mockResolvedValueOnce(findManyMock),
          findUnique: jest.fn().mockResolvedValue({}),
          update: jest.fn().mockResolvedValue({}),
          create: jest.fn().mockResolvedValue({}),
          delete: jest.fn().mockResolvedValue({}),
        },
      },
    },
  ],
}).compile();```

Hope you can resolve it