javascript - 使用 testdouble.js 的 mocha 测试模拟/ spy 导入库

标签 javascript node.js unit-testing

我的模块需要一个外部依赖:downloadjs导出一个函数而不是对象

import download from 'downloadjs' // download is a function

我的函数

const onExport = () => (dispatch, getState) => {
  let data = getState().get('data')
  let csv = mapDataToCsv(data)

  download(csv, "export-result.csv", "text/csv");
  // dispatch something else
}

单元测试

import download from 'downloadjs'
import td from 'testdouble'

// test case
it('unparse JSON to CSV', () => {
  td.replace('downloadjs') // no this doesn't work

  let store = createStore(reducer, initialState, middleware);
  store.dispatch(target.onExport()); // action calls

  let expected = td.matchers.contains('FOO,SUCCESS')
  // error it calls real download function not mock
  td.verify(download(expected, "export-result.csv", "text/csv")) 
  td.reset()
})

问题

我尝试模拟/替换 downloadjs 以验证它调用了有效数据。

td.replace(download)td.replace('downloadjs') 都不起作用

文档说你不应该模拟/替换外部库:

Why doesn't td.replace() work with external CommonJS modules?

那我该如何测试这段代码呢?

最佳答案

您可以围绕第 3 方库(在本例中为 downloadjs)中存在的功能创建一个包装器,并使用 td.replace 来模拟您的包装器。

你的函数

var downloadCSV = require('./downloadCSV.js')

module.exports = () => (dispatch, getState) => {
    downloadCSV('goats')
}

新的包装依赖

// downloadCSV.js
var download = require('downloadjs')

module.exports = (data) => {
    download(data, 'export-result.csv', 'text/csv')
}

单元测试

describe('csv exporter', () => {
    var subject, downloadCSV
    beforeEach(() => {
        downloadCSV = td.replace('../../lib/downloadCSV.js')
        subject     = require('../../lib/code.js')
    })

    describe('downloading csv', () => {
        it('works', () => {
            subject()()
            td.verify(downloadCSV('goats'))
        })
    });
});

笔记

  1. 请注意 subject()() 的两次调用,因为您有一个函数返回被测代码中的一个函数。

  2. 我使用了测试双重存储库中可用的 node 示例文件夹结构来构建这些测试:https://github.com/testdouble/testdouble.js/tree/master/examples/node

  3. 我已经上传了一个包含我的示例代码的存储库供您试用。 https://github.com/davemo/td-replace-helper

  4. 我没有包含特定于 Redux 的代码,也没有使用 ES6 样式导入,以避免在示例存储库中引入太多依赖项。

  5. 您可能需要修改 ES6 样式导入的使用,以便于使用 td.replace,查看此评论线程以获取更多信息:https://github.com/testdouble/testdouble.js/issues/51#issuecomment-207780628

关于javascript - 使用 testdouble.js 的 mocha 测试模拟/ spy 导入库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39607969/

相关文章:

javascript - 尝试从 'hover' CSS 过渡转换为类似的 javascript 功能。失败了

javascript - AngularJS - 如何从图像对象创建延迟对象

angularjs - 无需用户身份验证(无凭据)的安全 REST API

unit-testing - 使用 mvc api 和 ninject 进行单元测试

javascript - 使 Meteor 方法调用在客户端同步

javascript - 如何根据设备宽度更改下载按钮的 href 和 onclick 功能

javascript - Vuejs 应用程序显示无效的主机 header 错误循环

node.js - Mongoose QueryStream 新结果

java - 有人使用 Eclipse/Maven 的 JRuby 测试框架吗?

asp.net - 单元测试 http 处理程序?