用TypeScript在jest中模拟类依赖

2hh7jdfx  于 6个月前  发布在  Jest
关注(0)|答案(1)|浏览(64)

我正在使用ts-jest和Postgres。我有工作代码来模拟Pool()构造函数,池示例有一个query()方法,它返回一些模拟数据。

import { describe, expect, test } from "@jest/globals";
import { checkLimits } from "./db";
import { MINUTES } from "./constants";
const log = console.log;

// Make a mock for the pg Pool constructor
jest.mock("pg", () => {
  return {
    Pool: jest.fn(() => ({
      query: jest.fn(() => {
        return {
          rows: [
            {
              timestamps: [Date.now() - 10 * MINUTES],
            },
          ],
        };
      }),
    })),
  };
});

describe("checkLimits", () => {
  test("allows reasonable usage by address", async () => {
    await checkLimits("abcdef");
  });
});

字符串

此代码有效

我想做的是能够在我的测试中使用mockedQuery.mockReturnValueOnce(),但我尝试过,但没有成功。
所以我可以做:

describe("checkLimits", () => {
  test("allows reasonable usage by address", async () => {
    mockedQuery.mockReturnValueOnce({
      rows: [
        {
          timestamps: [Date.now() - 10 * MINUTES],
        },
      ],
    });
    await checkLimits("abcdef");
  });

  test("also allows on more usage", async () => {
    mockedQuery.mockReturnValueOnce({
      rows: [
        {
          timestamps: [
            Date.now() - 10 * MINUTES,
            Date.now() - 3 * MINUTES,
            Date.now() - 2 * MINUTES,
          ],
        },
      ],
    });
    await checkLimits("abcdef");
  });
});


然而,在JS提升问题,ts-jest弃用和其他复杂性之间,我似乎不能这样做。

如何在我的mocked Postgres实现中使用mockedQuery.mockReturnValueOnce()

1yjd4xko

1yjd4xko1#

我无法让mockReturnValueOnce()正常工作,但可以为模拟数据创建一个变量,并在每次测试后设置它。
如果其他人使用mockReturnValueOnce()发布答案,我会接受它。😊

import { describe, expect, test } from "@jest/globals";
import { Row, checkLimits } from "./db";
import { Pool } from "pg";
import { MINUTES } from "./constants";
const log = console.log;

let mockRows: Array<Row> = [];

// Make a mock for the pg Pool constructor
jest.mock("pg", () => {
  return {
    Pool: jest.fn(() => ({
      query: jest.fn(() => {
        return {
          rows: mockRows,
        };
      }),
    })),
  };
});

describe("checkLimits", () => {
  test("is fine when there's no previous usage", async () => {
    mockRows = [];
    await checkLimits("some ok value");
  });

  test("allows reasonable usage", async () => {
    mockRows = [...snip...];
    await checkLimits("some ok value");
  });

  test("blocks unreasonable usage", async () => {
    mockRows = [...snip...];
    await expect(checkLimits("some bad value")).rejects.toThrow(
      "some error"
    );
  });
});

字符串

相关问题