2
1

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で同じファイル内でfunctionがfunctionを呼ぶ時にどうやってstubするか?

Last updated at Posted at 2021-06-15

問題

utils.ts
function a() {
  return "a"
}

function b() {
  return a()
}

export { a, b }

例えばこういう風にb()a()を呼ぶような場合、

utils.test.ts
import {a, b} from "./utils"

jest.mock("./utils", () => {
  const original = jest.requireActual("./utils");
  return {
    ...original,
    a: jest.fn().mockReturnValue("modified a")
  };
});

describe("utils", () => {
  it("sholuld use mocked a()", () => {
    expect(b()).toEqual("modified a")
    expect(a).toHaveBeenCalledTimes(1)
  });
});

こうやってもexpect(b()).toEqual("modified a")でpassしない。

import * as utils from "./utils"
jest.spyOn(utils, 'a').mockImplementation(jest.fn().mockReturnValue("modified a"));

...

こうしても駄目。

どちらもb()はmockされていないutils.ts内のa()を呼ぶことになる。

解決

utils.ts
import * as utils from "./utils"  // 自分自身をimport 
            // import名は.test側と一致する必要はない

function a() {
  return "a"
}

function b() {
  return utils.a() // importしたものから呼び出す
}

export { a, b }
utils.test.ts
import * as utils from "./utils"

jest
  .spyOn(utils, "a")
  .mockImplementation(jest.fn().mockReturnValue("modified a"))

describe("utils", () => {
  it("sholuld use mocked a()", () => {
    expect(b()).toEqual("modified a")
    expect(a).toHaveBeenCalledTimes(1)
  });
});
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?