【发布时间】:2020-09-01 11:17:05
【问题描述】:
与Jest TypeError: is not a constructor in Jest.mock 类似,但我使用的是 ES6 导入 - 对这个问题的回答不适用于我的情况。
在the Jest .mock() documentation 之后,我试图从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: is not a constructor in Jest.mock 中给出的答案,但在这里失败了。
代码,只是:
const mockDbClient = new Client({ connectionString: env.DATABASE_URL });
失败:
TypeError: pg_1.Client is not a constructor
我注意到the docs mention __esModule: true is required when using default exports,但Client 不是pg 的默认导出(我已经检查过)。
如何让构造函数正常工作?
得到答案后的一些补充说明
这里有一个稍微长一点的答案版本,每行都有 cmets - 我希望阅读这篇文章的人觉得它有用!
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()
}
})
}
})
【问题讨论】:
标签: javascript typescript jestjs