【问题标题】:ES6 imports and 'is not a constructor' in Jest.mockJest.mock 中的 ES6 导入和“不是构造函数”
【发布时间】: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


    【解决方案1】:

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

    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')
      }))
    }));
    

    【讨论】:

    • 感谢雅各布!我学到的是 1. 模拟实现必须是一个对象,我们要导入的作为键。 2. 很明显,构造函数应该是一个函数。
    猜你喜欢
    • 1970-01-01
    • 2018-02-23
    • 2020-05-10
    • 2018-10-30
    • 2015-10-02
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    相关资源
    最近更新 更多