Jest.js 如何测试一个导入的函数返回一个玩笑中的承诺?

q8l4jmvw  于 2022-12-08  发布在  Jest
关注(0)|答案(1)|浏览(186)

我有一个非常简单的函数,我必须写一个测试,目标是满足覆盖率阈值。

import { lambdaPromise } from '@helpers';

export const main = async event => lambdaPromise(event, findUsers);

lambdaPromise()函数返回一个Promise。我试着模拟它,然后判断它是否被调用。下面是我得到的结果:

import { main, findUsers } from '../src/lambdas/user/findUsers';
import { lambdaPromise } from '@helpers';

const mockEvent = {
  arguments: {
    userDataQuery: {
      email: 'johndoe@whatever.com'
    }
  }
};

const mockLambdaPromise = jest.fn();

jest.mock('@helpers', () => ({
  lambdaPromise: jest.fn().mockImplementation(() => mockLambdaPromise)
}));

describe('findUsers', () => {
  it('should have a main function', async () => {
    const mockPromise = main(mockEvent);
    expect(mockPromise).toBeInstanceOf(Promise);
    expect(mockLambdaPromise).toBeCalledWith(mockEvent, findUsers);
  });
});

现在mockLambdaPromise永远不会被调用。如何解决这个问题?

sqxo8psd

sqxo8psd1#

你的mock返回一个函数,但是你没有调用这个函数。

jest.mock("./helpers", () => ({
  lambdaPromise: jest
    .fn()
    .mockImplementation((a, b) => mockLambdaPromise(a, b)),
}));

通过使用spy来模拟解析值,可以降低模拟的复杂性:

import { main, findUsers } from "./findUsers";
import * as helpers from "./helpers";

describe("findUsers", () => {
  it("should have a main function", async () => {
    const spy = jest.spyOn(helpers, "lambdaPromise").mockResolvedValue();
    await main(mockEvent);
    expect(spy).toBeCalledWith(mockEvent, findUsers);
  });
});

相关问题