LoginSignup
16
7

More than 5 years have passed since last update.

Jestのmockとimport記法を使う

Posted at

はじめに

ちょっと前まで、Jestではimportが利用できませんでした。
理由はbabelでimportをトランスパイルする際にrequireに変換するのですが、そのときにいろいろ問題があったようです。
そのため、私の場合は、automockを利用して、モック不要なものだけをdontMockする、という面倒な手法を利用していました。
しかし、jestがトランスパイルする際に、jest.mockを特別扱いするように変わりました。
(参考:https://facebook.github.io/jest/docs/ja/manual-mocks.html#es-module-import)

使い方

普通に使うだけです。

app.ts
import { foo, bar } from "./utils";
export function foobar() {
  return `${foo()}${bar()}`;
}
utils.ts
export function foo() {
  return "foo";
}

export function bar() {
  return "bar";
}
app.test.ts
import { foo, bar } from "../utils";
import { foobar } from "../app";

jest.mock("../../utils"); // ここが重要。

describe("foobar", function() {
  beforeAll(() => {
    (bar as jest.Mock).mockReturnsValue("foo");
  });
  it("when util.foo returns foo, sould returns foofoo", function() {
    expect(foobar()).toEqual("foofoo");
  });
});

サンプルはこちら

以上です。よろしくお願いいたします。

16
7
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
16
7