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

标签 javascript typescript jestjs

类似于 Jest TypeError: is not a constructor in Jest.mock ,除非我使用的是 ES6 导入 - 并且对该问题的答案不适用于我的情况。

关注 the Jest .mock() documentation我试图模拟构造函数 Client来自 pg模块。

我有一个构造函数,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 的默认导出(我已经检查过了)。

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

得到答案后的一些补充说明

这是答案的稍微长一点的版本,对每一行发生的事情都有评论——我希望阅读这篇文章的人觉得它有用!
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')
  }))
}));

关于javascript - Jest.mock 中的 ES6 导入和 'is not a constructor',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61822474/

相关文章:

unit-testing - Jest mock /监视 Mongoose 链式(查找、排序、限制、跳过)方法

node.js - 是否可以在 Node 中为没有 catch block 的 Promise 编写一个 Jest 单元测试?

javascript - Jquery - 如何检查 div 中的所有输入是否不为空?

javascript - 在 react 中显示加载百分比

typescript - 为什么 Webpack 5 包含我未使用的 TypeScript 枚举导出,即使启用了 Tree Shaking?

angular - 如何创建一个 Angular 2+ 组件并将其放在 npm 上

c# - MVC onfocusout 事件未触发

javascript - Ext js 4动态更改文本字段输入类型

javascript - 如何使用angular7关闭api响应的ngx-dialog?

reactjs - react 模拟测试 useNavigate