Sometimes when writing a unit test, you know that the module you're testing imports a module that you would like to observe, or at the very least mock to prevent side effects like network activity or file system operations.

For JavaScript unit tests that run in Node, we can hijack the built-in require function by using the proxyquire module, which allows us to mock one or more modules that are second-class dependencies in our unit test, replacing them with whatever we want.

This means we could replace functions with no-ops to prevent side effects, or replace them with Sinon spies to observe the inner workings of the module you're testing.

In this video, we'll demonstrate the basics of using Proxyquire to prevent and observe a file system operation.

index.js:

const fs = require('fs');

exports.writeFile = (filename, contents) => {
fs.writeFileSync(filename, contents.trim(), 'utf8');
}

For unit testing, we don't want to call 'fs.writeFileSync', instead we want to using mock function.

const assert = require('assert');
const proxyquire = require('proxyquire');
const sinon = require('sinon'); const fsMock = {};
// In index.js file, we want to mock 'fs' module with our fsMock object
const main = proxyquire('./index.js', {'fs', fsMock});
describe('main.writeFile', () => {
it('should write a trimmed string to the specififed file', () => {
fsMock.writeFileSync = sinon.spy();
main.writeFile('file.txt', 'string');
assert.deepEqual(fsMock.writeFileSync.getCall(0).args, ['file.txt', 'string', 'utf8'])
})
})

[Unit Testing] Mock a Node module's dependencies using Proxyquire的更多相关文章

  1. [Angular + Unit Testing] Mock HTTP Requests made with Angular’s HttpClient in Unit Tests

    In a proper unit test we want to isolate external dependencies as much as possible to guarantee a re ...

  2. [Unit Testing] Mock an HTTP request using Nock while unit testing

    When testing functions that make HTTP requests, it's not preferable for those requests to actually r ...

  3. [Unit Testing] Using Mockito Annotations - @Mock, @InjectMocks, @RunWith

    Previously we have seen how to do Unit testing with Mockito; import org.junit.Test; import static or ...

  4. [Java Basics3] XML, Unit testing

    What's the difference between DOM and SAX? DOM creates tree-like representation of the XML document ...

  5. C/C++ unit testing tools (39 found)---reference

    http://www.opensourcetesting.org/unit_c.php API Sanity AutoTest Description: An automatic generator ...

  6. Unit Testing a zend-mvc application

    Unit Testing a zend-mvc application A solid unit test suite is essential for ongoing development in ...

  7. Unit Testing PowerShell Code with Pester

    Summary: Guest blogger, Dave Wyatt, discusses using Pester to analyze small pieces of Windows PowerS ...

  8. Unit Testing of Spring MVC Controllers: “Normal” Controllers

    Original link: http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-m ...

  9. Unit Testing of Spring MVC Controllers: Configuration

    Original Link: http://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-m ...

随机推荐

  1. Codeforces Round #336 (Div. 2) A

    A. Saitama Destroys Hotel time limit per test 1 second memory limit per test 256 megabytes input sta ...

  2. bzoj 3507 DP+哈希

    [Cqoi2014]通配符匹配 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 541  Solved: 235[Submit][Status][Dis ...

  3. Linux下hdparm硬盘测速

    在Linux下可以使用hdparm对硬盘进行测试或者查看硬盘的相关信息.这样你就知道了硬盘读写速度. Hdparm功能说明:显示与设定硬盘的参数. 语 法:hdparm [-CfghiIqtTvyYZ ...

  4. Java基础复习--java.util.Timer定时任务

    在java中,Timer类主要用于定时性.周期性任务 的触发,这个类中有两个方法比较难理解,那就是schedule和scheduleAtFixedRate方法,在这里就用实例分析一下. (1)sche ...

  5. 汕头市队赛 SRM1X T2 ——扫描线

    绵津见-终 SRM 13 背景 “西瓜也是可以种在海上的!”——绵津见 然而种在海上的西瓜最需要防范的,是时不时会涌向瓜田的阵阵海浪. 幸好,身为海神的绵津见可以释放魔法“水平如镜”来阻止海浪拍打西瓜 ...

  6. malloc()与calloc区别【转】

    转自:http://blog.csdn.net/firecityplans/article/details/4490124/ 版权声明:本文为博主原创文章,未经博主允许不得转载. Both the m ...

  7. js5秒后自动关闭本页面及5秒钟后自动跳转指定页面的方法

    5秒钟后自动关闭 <!DOCTYPE HTML> <html> <head> <title>倒计时自动关闭/跳转页面</title> < ...

  8. 在Laravel中使用Middleware进行身份验证

    新建一个中间件: 方法写在handle中 判断用户是否登录而且是否是管理员,不是的话返回到主页 新建判断是否为管理员的方法 在kernel定义一个中间件,key是admin 注册群组路由:prefix ...

  9. Knockout 双向绑定的理解

    今天做了个需求就是上传图片,然后在代码中通过jQuery给一个标签赋值,经过前台的debug,发现这个值赋值成功了,但是提交到后台的请求里就没了,然后经历了一顿度娘,结果中发现了问题. 既然knock ...

  10. POJ 3264.Balanced Lineup-RMQ(ST)详解

    先写一道水题的博客,为后面要写的博客做一个铺垫. ヾ(◍°∇°◍)ノ゙ RMQ(Range Minimum/Maximum Query),即区间最值查询,对于长度为n的数列A,回答若干询问RMQ(A, ...