[英]ES6 imports and 'is not a constructor' in Jest.mock
Similar to Jest TypeError: is not a constructor in Jest.mock , except I am using ES6 imports - and the answer given to that question is not working on my situation.类似于Jest TypeError: is not a constructor in Jest.mock ,除了我使用的是 ES6 导入 - 并且对该问题的答案不适用于我的情况。
Following the Jest .mock()
documentation I am attempting to mock the constructor Client
from the pg
module.按照Jest .mock()
文档,我试图从pg
模块模拟构造函数Client
。
I have a constructor, Client
, imported from an ES6 module called pg
.我有一个构造函数Client
,它是从名为pg
的 ES6 模块导入的。 Instances of Client
should have a query
method. 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]
}
Here's my __tests__/test.ts
这是我的__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'])
});
This is similar to the answer given in Jest TypeError: is not a constructor in Jest.mock , but it's failing here.这类似于Jest TypeError: is not a constructor in Jest.mock 中给出的答案,但在这里失败了。
The code, just:代码,只是:
const mockDbClient = new Client({ connectionString: env.DATABASE_URL });
fails with:失败:
TypeError: pg_1.Client is not a constructor
I note the docs mention __esModule: true
is required when using default exports , but Client
is not a default export from pg
(I've checked).我注意到文档提到__esModule: true
is required when using default exports ,但Client
不是pg
的默认导出(我已经检查过)。
How can I make the constructor work properly?如何使构造函数正常工作?
Here's a slightly longer-form version of the answer, with comments about what's happening on each line - I hope people reading this find it useful!这是答案的稍微长一点的版本,对每一行发生的事情都有评论——我希望阅读这篇文章的人觉得它有用!
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()
}
})
}
})
When you mock the module, it needs to have the same shape as the actual module.当您模拟模块时,它需要与实际模块具有相同的形状。 Change:改变:
jest.mock("pg", () => {
return {
query: jest
.fn()
.mockReturnValueOnce('one')
.mockReturnValueOnce('two'),
};
});
...to: ...至:
jest.mock("pg", () => ({
Client: jest.fn().mockImplementation(() => ({
query: jest.fn()
.mockReturnValueOnce('one')
.mockReturnValueOnce('two')
}))
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.