Ensure Functions are Called Correctly with JavaScript Mocks

Often when writing JavaScript tests and mocking dependencies, you’ll want to verify that the function was called correctly. That requires keeping track of how often the function was called and what arguments it was called with. That way we can make assertions on how many times it was called and ensure it was called with the right arguments.

Function to be mocked: utils.js

// returns the winning player or null for a tie
// Let's pretend this isn't using Math.random() but instead
// is making a call to some third party machine learning
// service that has a testing environment we don't control
// and is unreliable so we want to mock it out for tests.
function getWinner(player1, player2) {
const winningNumber = Math.random();
return winningNumber < 1 / 3
? player1
: winningNumber < 2 / 3
? player2
: null;
} module.exports = {getWinner};

Implementaion: thumbwar.js

const utils = require("./utils");

function thumbWar(player1, player2) {
const numberToWin = 2;
let player1Wins = 0;
let player2Wins = 0;
while (player1Wins < numberToWin && player2Wins < numberToWin) {
const winner = utils.getWinner(player1, player2);
if (winner === player1) {
player1Wins++;
} else if (winner === player2) {
player2Wins++;
}
}
return player1Wins > player2Wins ? player1 : player2;
} module.exports = thumbWar;

Testing:

const thumbWar = require("./thumbwar");
const utils = require("./utils");
const assert = require("assert"); test("returns winner", () => {
const originalGetWinner = utils.getWinner;
utils.getWinner = jest.fn((p1, p2) => p1); // eslint-disable-line no-unused-vars
const winner = thumbWar("KCD", "KW");
expect(winner).toBe("KCD");
// check the params are correct
expect(utils.getWinner.mock.calls).toEqual([["KCD", "KW"], ["KCD", "KW"]]);
// check the fn has been called number of times
expect(utils.getWinner).toHaveBeenCalledTimes(2);
// check each time call the fn with the correct params
expect(utils.getWinner).toHaveBeenNthCalledWith(1, "KCD", "KW");
expect(utils.getWinner).toHaveBeenNthCalledWith(2, "KCD", "KW"); utils.getWinner = originalGetWinner;
});

Here we are using 'jest.fn' to mock the function.

We can also create a mock fn by ourselves.

function fn(impl) {
const mockFn = (...args) => {
mockFn.mock.calls.push(args);
return impl(...args);
};
mockFn.mock = {calls: []};
return mockFn;
}
test("returns winner: fn", () => {
const originalGetWinner = utils.getWinner;
utils.getWinner = fn((p1, p2) => p1); // eslint-disable-line no-unused-vars
const winner = thumbWar("KCD", "KW");
assert.strictEqual(winner, "KCD");
assert.deepStrictEqual(utils.getWinner.mock.calls, [
["KCD", "KW"],
["KCD", "KW"],
]);
utils.getWinner = originalGetWinner;
});

Restore the Original Implementation of a Mocked JavaScript Function with jest.spyOn

With our current usage of the mock function we have to manually keep track of the original implementation so we can cleanup after ourselves to keep our tests idempotent (moonkey patching). Let’s see how jest.spyOn can help us avoid the bookkeeping and simplify our situation.

test("returns winner", () => {
//const originalGetWinner = utils.getWinner;
//utils.getWinner = jest.fn((p1, p2) => p1); // eslint-disable-line no-unused-vars
jest.spyOn(utils, "getWinner");
utils.getWinner.mockImplementation((p1, p2) => p1); // eslint-disable-line no-unused-vars
const winner = thumbWar("KCD", "KW");
expect(winner).toBe("KCD");
expect(utils.getWinner.mock.calls).toEqual([["KCD", "KW"], ["KCD", "KW"]]);
expect(utils.getWinner).toHaveBeenCalledTimes(2);
expect(utils.getWinner).toHaveBeenNthCalledWith(1, "KCD", "KW");
expect(utils.getWinner).toHaveBeenNthCalledWith(2, "KCD", "KW"); // utils.getWinner = originalGetWinner;
utils.getWinner.mockRestore();
});

Here we are using jest.spyOn function.

We can also write spyOn function by ourselves.

function fn(impl = () => {}) {
const mockFn = (...args) => {
mockFn.mock.calls.push(args);
mockFn.mockImplementation = newImpl => (impl = newImpl);
return impl(...args);
};
mockFn.mock = {calls: []};
return mockFn;
} function spyOn(obj, prop) {
// store the origianl fn
const originalValue = obj[prop];
// assign new mock fn
obj[prop] = fn;
// add restore fn
obj[prop].mockRestore = () => (obj[prop] = originalValue);
} test("returns winner: fn", () => {
spyOn(utils, "getWinner");
utils.getWinner.mockImplementation = fn((p1, p2) => p1); // eslint-disable-line no-unused-vars
const winner = thumbWar("KCD", "KW");
assert.strictEqual(winner, "KCD");
assert.deepStrictEqual(utils.getWinner.mock.calls, [
["KCD", "KW"],
["KCD", "KW"],
]);
utils.getWinner.mockRestore();
});

Mock a JavaScript module in a test

So far we’re still basically monkey-patching the utils module which is fine, but could lead to problems in the future, especially if we want to mock a ESModule export which doesn’t allow this kind of monkey-patching on exports. Instead, let’s mock the entire module so when our test subject requires the file they get our mocked version instead.

To mock a whole module. we can use 'jest.mock':

const thumbWar = require("./thumbwar");
const utils = require("./utils");
const assert = require("assert"); jest.mock("./utils", () => {
return {
getWinner: jest.fn((p1, p2) => p1), // eslint-disable-line no-unused-vars
};
}); test("returns winner", () => { const winner = thumbWar("KCD", "KW");
expect(winner).toBe("KCD");
expect(utils.getWinner.mock.calls).toEqual([["KCD", "KW"], ["KCD", "KW"]]);
expect(utils.getWinner).toHaveBeenCalledTimes(2);
expect(utils.getWinner).toHaveBeenNthCalledWith(1, "KCD", "KW");
expect(utils.getWinner).toHaveBeenNthCalledWith(2, "KCD", "KW"); utils.getWinner.mockReset();
});

Now we don't need to mock the 'getWinner' function inside test, 'jest.mock' can be used anywhere, jest will make sure it mock will be hoisted to the top.

Make a shared JavaScript mock module

Often you’ll want to mock the same file throughout all the tests in your codebase. So let’s make a shared mock file in Jest's __mocks__ directory which Jest can load for us automatically.

__mocks__/utils.js:

module.exports = {
getWinner: jest.fn((p1, p2) => p1), // eslint-disable-line no-unused-vars
};
const thumbWar = require("../thumbwar");
const utils = require("../utils");
const assert = require("assert"); jest.mock("../utils"); test("returns winner", () => {
const winner = thumbWar("KCD", "KW");
expect(winner).toBe("KCD");
expect(utils.getWinner.mock.calls).toEqual([["KCD", "KW"], ["KCD", "KW"]]);
expect(utils.getWinner).toHaveBeenCalledTimes(2);
expect(utils.getWinner).toHaveBeenNthCalledWith(1, "KCD", "KW");
expect(utils.getWinner).toHaveBeenNthCalledWith(2, "KCD", "KW"); utils.getWinner.mockReset();
});

[Testing] JavaScript Mocking Fundamentals的更多相关文章

  1. Googletest - Google Testing and Mocking Framework

    Googletest - Google Testing and Mocking Framework https://github.com/google/googletest

  2. [Testing] Static Analysis Testing JavaScript Applications

    The static code analysis and linting tool ESLint is the de-facto standard for linting JavaScript pro ...

  3. 12款简化 Web 开发的 JavaScript 开发框架

    前端框架简化了开发过程中,像 Bootstrap 和 Foundation 就是前端框架的佼佼者.在这篇文章了,我们编制了一组新鲜的,实用的,可以帮助您建立高质量的 Web 应用程序的 JavaScr ...

  4. JavaScript测试工具比较: QUnit, Jasmine, and Mocha

    1. QUnit A JavaScript Unit Testing framework. QUnit is a powerful, easy-to-use JavaScript unit testi ...

  5. 15款加速 Web 开发的 JavaScript 框架

    JavaScript 可以通过多种方式来创建交互式的网站和 Web 应用程序.利用 JavaScript,可以让你移动 HTML 元素,创建各种各样的自定义动画,给你的访问者更好的终端用户体验. 对于 ...

  6. 关于JavaScript测试工具:QUnit, Jasmine, MoCha

    在进行前端开发过程中,在某些场景下,需要通过编写单元测试来提高代码质量.而JavaScript常用的单元测试框架有这几个:QUnit, Jasmine, MoCha.下面就基于这三个工具,简单做一比较 ...

  7. Top JavaScript Frameworks, Libraries & Tools and When to Use Them

    It seems almost every other week there is a new JavaScript library taking the web community by storm ...

  8. 近期流行的JavaScript框架与主题

    [新年快乐]2017年你应该关注的JavaScript框架与主题 2017-01-01 王下邀月熊 JavaScript JavaScript的繁荣促生了很多优秀的技术.框架与工具库,这空前的繁荣也给 ...

  9. JavaScript引擎基本原理: 优化prototypes

    原文链接: JavaScript engine fundamentals: optimizing prototypes 这篇文章介绍了一些JavaScript引擎常用的优化关键点, 并不只是Bened ...

随机推荐

  1. 网络设备之ospf2

    OSPF(Open Shortest Pass First,开放最短路径优先协议),是一个最常用的内部网管协议,是一个链路状态协议. OSPF的特点 OSPF是一种无类路由协议,支持VLSM可变长子网 ...

  2. mysql 导入数据库

    1:创建数据库 dos 进入 xxx\MySQL5.7\bin 目录(很多人喜欢把这个路径配置在环境变量path中,这样在dos敲命令时,就直接是mysql......) mysql -uroot - ...

  3. RN笔记

    https://facebook.github.io/react-native/docs/using-a-listview.html react native类似于react,不过它使用的是原生组件, ...

  4. TB平台搭建之三

    有简单到复杂,可以简单的决不复杂化,事情从可控开始,即使再好的技术如果不可控最好不要用否则以后的debug可能比较麻烦. 无论是搭建平台还是写复杂的case都是尽量从简单开始,不要上来复杂,否则deb ...

  5. PHP发送邮件标题乱码的解决

    遇到问题:PHPMailer发送邮件时中文乱码,本来我的系统都是英文内容的,后来需求变化需要在标题中添加中文,但是在使用安卓自带邮件工具收取是出现乱码,而使用QQ邮箱查看确实正常的. 解决方法: 先用 ...

  6. bash初识,特性,用法/网站

    目录 一.Bash初识 Bash Shell介绍 Bash Shell的作用 Bash 两种方式 命令提示符 二.Shell的基本语法 三.Shell的基本特性 1.命令补全 tab 2. Linux ...

  7. 我的Python分析成长之路3

    一 集合                                                                                                 ...

  8. Luogu3195 [HNOI2008]玩具装箱TOY (方程变形 + 斜率优化 )

    题意: 给出一个序列 {a[i]} 把其分成若干个区间,每个区间的价值为 W = (j − i + ∑ak(i<=k<=j) - L)​2 ,求所有分割方案中价值之和的最小值. 细节: 仔 ...

  9. FastJson生成json时,显示Null属性

    FastJson生成json时,默认不会输出null字段. 移动端,有时候,需要后端提供完整的字段说明. Map < String , Object > jsonMap = new Has ...

  10. CSU-1336: Interesting Calculator,最短路思想!

    1336: Interesting Calculator 这道题被LZQ抢了一血,于是去读题发现题意不难,纯广搜结果写的一塌糊涂. 题意:给你两个数x,y.由x每次可以经过一系列操作变换,每个变换都有 ...