ES6 导入和 Jest.mock 中的'is not a constructor'



类似于Jest TypeError:不是Jest.mock中的构造函数,除了我使用的是ES6导入 - 并且给出的答案不适用于我的情况。

按照 Jest.mock()文档,我试图从pg模块模拟构造函数Client

我有一个构造函数,Client,从一个名为pg的 ES6 模块导入。Client的实例应具有query方法。

import { Client } from "pg";
new Client({ connectionString: 'postgresql://postgres:postgres@localhost:5432/database' });
export async function doThing(client): Promise<string[]> {
var first = await client.query('wooo')
var second = await client.query('wooo')
return [first, second]
}

这是我的__tests__/test.ts

const log = console.log.bind(console)
jest.mock("pg", () => {
return {
query: jest
.fn()
.mockReturnValueOnce('one')
.mockReturnValueOnce('two'),
};
});
import { Client } from "pg";
import { doThing } from "../index";
it("works", async () => {
let client = new Client({});
var result = await doThing(client);
expect(result).toBe(['one', 'two'])
});

这类似于Jest TypeError中给出的答案:不是Jest.mock中的构造函数,但它在这里失败了。

代码,只是:

const mockDbClient = new Client({ connectionString: env.DATABASE_URL });

失败,并显示:

TypeError: pg_1.Client is not a constructor

我注意到文档提到使用默认导出时需要__esModule: true,但Client不是pg的默认导出(我已经检查过(。

如何使构造函数正常工作?

得到答案后的一些附加说明

这是一个稍微长一些的答案版本,对每行发生的事情都有评论 - 我希望阅读本文的人发现它有用!

jest.mock("pg", () => {
// Return the fake constructor function we are importing
return {
Client: jest.fn().mockImplementation(() => {
// The consturctor function returns various fake methods
return {
query: jest.fn()
.mockReturnValueOnce(firstResponse)
.mockReturnValueOnce(secondResponse),
connect: jest.fn()
}
})
}
})

当您模拟模块时,它需要具有与实际模块相同的形状。改变:

jest.mock("pg", () => {
return {
query: jest
.fn()
.mockReturnValueOnce('one')
.mockReturnValueOnce('two'),
};
});

。自:

jest.mock("pg", () => ({
Client: jest.fn().mockImplementation(() => ({
query: jest.fn()
.mockReturnValueOnce('one')
.mockReturnValueOnce('two')
}))
}));

相关内容

最新更新