2023-04-23 jest.spyOn / jest.fn(implementation)
jest のモックの方法をメモ。
まず、オリジナルの挙動を挙動を上書きするのであれば下記二つの関数が使える。
jest.spyOn(object, methodName).mockImplementation(() => customImplementation)
jest.replaceProperty(object, methodName, jest.fn(() => customImplementation))
If you want to overwrite the original function, you can use
jest.spyOn(object, methodName).mockImplementation(() => customImplementation)
orjest.replaceProperty(object, methodName, jest.fn(() => customImplementation));
const video = { play() { return true; }, }; module.exports = video;
const video = require('./video'); afterEach(() => { // restore the spy created with spyOn jest.restoreAllMocks(); }); test('plays video', () => { const spy = jest.spyOn(video, 'play'); const isPlaying = video.play(); expect(spy).toHaveBeenCalled(); expect(isPlaying).toBe(true); });
使用例: GitHub APIをモックする
const setup = (list: jest.Mock) => {
const getOctokit = jest.fn().mockImplementation(() => {
const { GitHub } = jest.requireActual("@actions/github/lib/utils");
return {
...GitHub,
rest: {
pulls: { list: list },
},
};
});
jest.spyOn(github, "getOctokit").mockImplementation(getOctokit);
return [getOctokit];
};
ref. Github API を呼び出す JavaScript Action using TypeScript のテストを書く Tips
jest.fn(implementation)
Tipsとしては、jest.fn().mockImplementation(implementation)
は jest.fn(implementation)
に置き換え可能。
jest.fn(implementation)
is a shorthand forjest.fn().mockImplementation(implementation)
.
ref. モック関数 · Jest