LoginSignup
11
11

More than 5 years have passed since last update.

jestのmockを有効活用する

Last updated at Posted at 2017-10-01

jestでテストするときはautomockをオンにするとよい

という話を書いたのですが、どうやって使うのかを書き忘れたので、こちらに書いておきます。
http://qiita.com/naokitomita/items/c60d201671d001333ee9

app.js
import { hoge, fuga } from "../utils";

export function hogefuga() {
  return hoge() + fuga(2);
}
utils.js
export hoge() {
  return "hoge";
}

export fuga() {
  return "fuga";
}

テスト

__test__/app.test.js
import { hogefuga } from "../app";
import { hoge, fuga } from "../utils";
jest.unmock("../app");

describe("app", () => {
  describe("#hogefuga", () => {
    describe("hoge, fuga returns hoge each.", () => {
      beforeAll(() => {
        // hoge, fugaは
        // https://facebook.github.io/jest/docs/en/mock-function-api.html
        // ↑に記述されているmockに置き換わっています。
        hoge.mockReturnValue("hoge"); // hogeを返すように設定しておいたり
        fuga.mockImplementation((p) => { // 実装を定義したりできます
          console.log("fuga called with: " + p);
          return "fuga";
        });
      });

      it("shuld returns hogefuga", () => {
        expect(hogefuga()).toEqual("hogefuga");
        expect(hoge.mock.calls.length).toBe(1); // 呼び出し回数
        expect(fuga.mock.calls[0][0]).toBe(2); // 1番目に呼ばれたときの第1引数のチェック
      });
    });
  });
});

参考

https://github.com/naoki-tomita/jest-mock-test
ここにサンプルを置いておきました。

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