使用 Jest 覆盖各个测试中的函数

有时您想在某些测试中模拟某个函数,但不想在其他测试中模拟。有时您想为不同的测试提供不同的模拟。 jest 使这变得棘手:它的默认行为是覆盖整个测试文件的包函数,而不仅仅是单个测试。如果您使用过 python 的 @patch 或 lara

使用 jest 覆盖各个测试中的函数

有时您想在某些测试中模拟某个函数,但不想在其他测试中模拟。有时您想为不同的测试提供不同的模拟。 jest 使这变得棘手:它的默认行为是覆盖整个测试文件的包函数,而不仅仅是单个测试。如果您使用过 python 的 @patch 或 laravel 的服务容器等灵活工具,这似乎很奇怪。

这篇文章将向您展示如何模拟单个测试的函数,然后在未提供模拟的情况下回退到原始实现。将给出 commonjs 和 es 模块的示例。本文中演示的技术适用于第一方模块和第三方包。

commonjs 与 es 模块

由于我们将在这篇文章中介绍多个模块系统,因此了解它们是什么很重要。

commonjs(简称cjs)是node.js中的模块系统。它使用 module.exports 导出函数并使用 require() 导入函数:

// commonjs export 

function greet() {
  return "hello, world!";
}

module.exports = { greet };

登录后复制

// commonjs import

const getuserslist = require('./greet');

登录后复制

es 模块(缩写为 esm)是浏览器使用的模块系统。它使用export关键字导出函数并使用import关键字导入函数:

// es module export

export default function greet() {
  return "hello, world!";
}

登录后复制

// es module import

import { greet } from "./greet";

登录后复制

在撰写本文时,大多数前端 javascript 开发人员都使用 es 模块,许多服务器端 js 开发人员也使用它们。然而,commonjs 仍然是 node 的默认设置。无论您使用哪个系统,都值得阅读整篇文章来了解 jest 的模拟系统。

使用 commonjs 模拟单个导出函数

通常,commonjs 文件将使用对象语法导出其模块,如下所示:

// commonjs export 

function greet() {
  return "hello, world!";
}

module.exports = { greet: greet };

登录后复制

但是,也可以自行导出函数:

// commonjs export 

function greet() {
  return "hello, world!";
}

module.exports = greet;

登录后复制

我不一定建议在您自己的代码中执行此操作:导出对象会让您在开发应用程序时减少一些麻烦。然而,这种情况很常见,值得讨论如何在 commonjs 中模拟裸导出的函数,然后在测试未提供自己的实现时回退到原始函数。

假设我们有以下 commonjs 文件,我们想在测试期间模拟:

// cjsfunction.js

function testfunc() {
  return "original";
}

module.exports = testfunc;

登录后复制

我们可以使用以下代码在测试中模拟它:

const testfunc = require("./cjsfunction");

jest.mock("./cjsfunction");

beforeeach(() => {
  testfunc.mockimplementation(jest.requireactual("./cjsfunction"));
});

it("can override the implementation for a single test", () => {
  testfunc.mockimplementation(() => "mock implementation");

  expect(testfunc()).tobe("mock implementation");
  expect(testfunc.mock.calls).tohavelength(1);
});

it("can override the return value for a single test", () => {
  testfunc.mockreturnvalue("mock return value");

  expect(testfunc()).tobe("mock return value");
  expect(testfunc.mock.calls).tohavelength(1);
});

it("returns the original implementation when no overrides exist", () => {
  expect(testfunc()).tobe("original");
  expect(testfunc.mock.calls).tohavelength(1);
});

登录后复制

怎么运行的

当我们调用 jest.mock(“./cjsfunction”) 时,这会用自动模拟(文档)替换模块(文件及其所有导出)。当调用自动模拟时,它将返回未定义。但是,它将提供用于覆盖模拟的实现、返回值等的方法。你可以在 jest mock functions 文档中看到它提供的所有属性和方法。

我们可以使用mock的mockimplementation()方法自动将mock的实现设置为原始模块的实现。 jest 提供了一个 jest.requireactual() 方法,该方法将始终加载原始模块,即使它当前正在被模拟。

mock 实现和返回值在每次测试后都会自动清除,因此我们可以将回调函数传递给 jest 的 beforeeach() 函数,该函数在每次测试前将模拟的实现设置为原始实现。然后,任何希望提供自己的返回值或实现的测试都可以在测试主体中手动执行此操作。

导出对象时模拟 commonjs

假设上面的代码导出了一个对象而不是单个函数:

// cjsmodule.js

function testfunc() {
  return "original";
}

module.exports = {
  testfunc: testfunc,
};

登录后复制

我们的测试将如下所示:

const cjsmodule = require("./cjsmodule");

aftereach(() => {
  jest.restoreallmocks();
});

it("can override the implementation for a single test", () => {
  jest
    .spyon(cjsmodule, "testfunc")
    .mockimplementation(() => "mock implementation");

  expect(cjsmodule.testfunc()).tobe("mock implementation");
  expect(cjsmodule.testfunc.mock.calls).tohavelength(1);
});

it("can override the return value for a single test", () => {
  jest.spyon(cjsmodule, "testfunc").mockreturnvalue("mock return value");

  expect(cjsmodule.testfunc()).tobe("mock return value");
  expect(cjsmodule.testfunc.mock.calls).tohavelength(1);
});

it("returns the original implementation when no overrides exist", () => {
  expect(cjsmodule.testfunc()).tobe("original");
});

it("can spy on calls while keeping the original implementation", () => {
  jest.spyon(cjsmodule, "testfunc");

  expect(cjsmodule.testfunc()).tobe("original");
  expect(cjsmodule.testfunc.mock.calls).tohavelength(1);
});

登录后复制

怎么运行的

jest.spyon() 方法允许 jest 记录对对象方法的调用并提供自己的替换。这适用于对象,我们可以使用它,因为我们的模块正在导出包含我们的函数的对象。

spyon() 方法是一个模拟方法,因此必须重置其状态。 jest spyon() 文档建议在 aftereach() 回调中使用 jest.restoreallmocks() 重置状态,这就是我们上面所做的。如果我们不这样做,则在调用spyon()后,模拟将在下一次测试中返回未定义。

模拟es模块

es 模块可以有默认的和命名的导出:

// esmmodule.js

export default function () {
  return "original default";
}

export function named() {
  return "original named";
}

登录后复制

上面文件的测试如下所示:

import * as esmmodule from "./esmmodule";

aftereach(() => {
  jest.restoreallmocks();
});

it("can override the implementation for a single test", () => {
  jest
    .spyon(esmmodule, "default")
    .mockimplementation(() => "mock implementation default");
  jest
    .spyon(esmmodule, "named")
    .mockimplementation(() => "mock implementation named");

  expect(esmmodule.default()).tobe("mock implementation default");
  expect(esmmodule.named()).tobe("mock implementation named");

  expect(esmmodule.default.mock.calls).tohavelength(1);
  expect(esmmodule.named.mock.calls).tohavelength(1);
});

it("can override the return value for a single test", () => {
  jest.spyon(esmmodule, "default").mockreturnvalue("mock return value default");
  jest.spyon(esmmodule, "named").mockreturnvalue("mock return value named");

  expect(esmmodule.default()).tobe("mock return value default");
  expect(esmmodule.named()).tobe("mock return value named");

  expect(esmmodule.default.mock.calls).tohavelength(1);
  expect(esmmodule.named.mock.calls).tohavelength(1);
});

it("returns the original implementation when no overrides exist", () => {
  expect(esmmodule.default()).tobe("original default");
  expect(esmmodule.named()).tobe("original named");
});

登录后复制

怎么运行的

这看起来几乎与前面的 commonjs 示例相同,但有几个关键区别。

首先,我们将模块作为命名空间导入。

import * as esmmodule from "./esmmodule";

登录后复制

然后当我们想要监视默认导出时,我们使用“default”:

  jest
    .spyon(esmmodule, "default")
    .mockimplementation(() => "mock implementation default");

登录后复制

es 模块导入故障排除

有时尝试使用第三方包调用 jest.spyon() 时,你会收到如下错误:

    typeerror: cannot redefine property: usenavigate
        at function.defineproperty (<anonymous>)
</anonymous>

登录后复制

当您遇到此错误时,您需要模拟导致问题的包:

import * as reactrouterdom from "react-router-dom";

// add this:
jest.mock("react-router-dom", () =&gt; {
  const originalmodule = jest.requireactual("react-router-dom");

  return {
    __esmodule: true,
    ...originalmodule,
  };
});

aftereach(() =&gt; {
  jest.restoreallmocks();
});

登录后复制

此代码将模块替换为 jest es 模块模拟,其中包含使用 jest.mocks 的工厂参数的模块的所有原始属性。每当在 jest.mock 中使用工厂参数来模拟 es 模块时,都需要 __esmodule 属性(文档)。

如果需要,您还可以替换工厂参数中的单个函数。例如,如果消费者在 router 上下文之外调用 usenavigate(),react router 将抛出错误,因此如果需要,我们可以使用 jest.mock() 在整个测试文件中替换该函数:

jest.mock("react-router-dom", () =&gt; {
  const originalModule = jest.requireActual("react-router-dom");

  return {
    __esModule: true,
    ...originalModule,

    // Dummy that does nothing.
    useNavigate() {
      return function navigate(_location) {
        return;
      };
    },
  };
});

登录后复制

包起来

我希望这些信息在您编写自己的测试时很有价值。当测试本身未提供实现时,并非每个应用程序都会受益于能够回退到默认实现。事实上,许多应用程序希望对整个测试文件使用相同的模拟。然而,这篇文章中展示的技术将使您能够对模拟进行细粒度的控制。

如果我遗漏了某些内容,或者是否有我没有包含在这篇文章中的内容,请告诉我。

以上就是使用 Jest 覆盖各个测试中的函数的详细内容,更多请关注叮当号网其它相关文章!

文章来自互联网,只做分享使用。发布者:代号邱小姐,转转请注明出处:https://www.dingdanghao.com/article/689248.html

(0)
上一篇 2024-08-06 22:19
下一篇 2024-08-06 22:19

相关推荐

联系我们

在线咨询: QQ交谈

邮件:442814395@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信公众号