6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Jestでモジュールの特定の関数だけモックする

Posted at

Jestでモジュールをモックするのは便利ですが、モジュールの一部をモックしたい場合に困ることがあります。

// my-module.js
export function foo() { ... }
export function bar() { ... } // bar だけモックしたい
import { foo, bar } from "./my-module";

jest.mock("./my-module", () => ({
  bar: jest.fn(),
}));

describe("foo", () => {
  it("works", () => {
    expect(foo("yay")).toEqual("wow");
  });
});

上記のように書いた場合に、 TypeError: foo is not a function といったエラーになってしまいます。それを回避するには以下のように書きます。

jest.mock("./my-module", () => ({
  ...jest.requireActual("./my-module"), // foo: jest.requireActual("./my-module").foo でも可
  bar: jest.fn(),
}));

Jest的に認められた書き方なのかは怪しいですがとりあえず bar をモックして foo はモックせず動かせます :sunglasses:

参照

https://github.com/facebook/jest/issues/936#issuecomment-613220940
https://jestjs.io/docs/en/jest-object#jestrequireactualmodulename

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?