Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

express - Jest / Unit test failing on the function which returns a asyncronous method

I'm using TypeORM.
It works fine at the local with real DB connection.

But when I run the test with Jest, the test gets failed.
I mocked the TypeORM method I needed, and expected all these methods to be called.

Test is failing on expect(typeorm.getRepository(Covid).save).toHaveBeenCalled();
it is not being called.

I cannot understand why this test code is not calling.

Does anyone know the solution?

Here is the code.

describe('getCoronaData', () => {
  it('should get a Covid Status data and return it', async () => {
    typeorm.getRepository = jest.fn().mockReturnValue({
      findOne: jest.fn().mockResolvedValue(null),
      create: jest.fn(),
      save: jest.fn(),
    });

    await getCoronaData();

    expect(typeorm.getRepository).toHaveBeenCalledWith(Covid);
    expect(typeorm.getRepository(Covid).findOne).toHaveBeenCalled();
    expect(typeorm.getRepository(Covid).save).toHaveBeenCalled(); // this expect result is making an error
                                                                  // Expected number of calls: >= 1
                                                                  // Received number of calls:    0
  });
});
question from:https://stackoverflow.com/questions/65918365/jest-unit-test-failing-on-the-function-which-returns-a-asyncronous-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Self-answer

I found the problem why the test failing. forEach() method should not be used with async/await.
so I just changed the code using Promise.all() and map()

await Promise.all(
      covidStatus.map(async (status) => {
        const exist = await covidRepository.findOne({
          where: { city: status.city },
        });
        if (!exist) {
          const newData = covidRepository.create({
            city: status.city,
            totalCases: status.totalCases,
            increasedCases: status.increasedCases,
            date: $standardTime,
          });
          return covidRepository.save(newData);
        } else {
          return covidRepository.save([
            {
              id: exist.id,
              totalCases: status.totalCases,
              increasedCases: status.increasedCases,
              date: $standardTime,
            },
          ]);
        }
      })
    );

Or

    for (const status of covidStatus) {
      const exist = await covidRepository.findOne({
        where: { city: status.city },
      });
      if (!exist) {
        const newData = covidRepository.create({
          city: status.city,
          totalCases: status.totalCases,
          increasedCases: status.increasedCases,
          date: $standardTime,
        });
        return covidRepository.save(newData);
      } else {
        return covidRepository.save([
          {
            id: exist.id,
            totalCases: status.totalCases,
            increasedCases: status.increasedCases,
            date: $standardTime,
          },
        ]);
      }
    }

I found this solution from Here.

using forEach and async/await, behaves different for node and Jest


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...