博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Unit Testing] Mock a Node module's dependencies using Proxyquire
阅读量:6824 次
发布时间:2019-06-26

本文共 1491 字,大约阅读时间需要 4 分钟。

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  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  to prevent side effects, or replace them with  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 objectconst 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'])  })})

 

转载地址:http://rxrzl.baihongyu.com/

你可能感兴趣的文章
Tor 项目弃用 obfs2,开发 obfs4
查看>>
Eclipse设置:背景与字体大小和xml文件中字体大小调整
查看>>
c++强制类型转换(总结)
查看>>
H3C S5500 配置范例
查看>>
工具05:XShell
查看>>
SQL分割字符串详解
查看>>
Apache+Resin整合搭建JSP环境
查看>>
【C/C++学院】(4)c++开篇/类和对象/命名空间/类型增强/三目运算符/const专题/引用专题/函数增强...
查看>>
【踩坑经历】一次Asp.NET小网站部署踩坑和解决经历
查看>>
通过python切换hosts文件
查看>>
iOS8新特性扩展(Extension)应用之四——自定义键盘控件
查看>>
窥探Swift之函数与闭包的应用实例
查看>>
数据对接—kettle使用之九
查看>>
tableVIew删除时的delete按钮被挡住时重写的方法
查看>>
【AIX 命令学习】mkdev -l 设置逻辑卷
查看>>
[curl-loader]faststart新压力测试工具
查看>>
政策 |《关于组织实施促进大数据发展重大工程》的通知
查看>>
java抽象类与接口的区别
查看>>
自建JS代码库(1)---添加用户的常用验证
查看>>
Module Thinking之路径依赖
查看>>