在Node中模拟依赖项 [英] Mocking a dependency in Node

查看:61
本文介绍了在Node中模拟依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Node.js,想知道人们在进行单元测试时如何嘲笑模块中的依赖关系.

I'm in the process of learning Node.js and am wondering about how people mock dependencies in their modules when unit testing.

例如: 我有一个抽象MongoDB调用的模块.使用此模块的模块可能会开始如下所示.

For example: I have a module that abstracts my MongoDB calls. A module that uses this module may start out something like this.

var myMongo = require("MyMongoModule");
// insert rest of the module here.

我想确保我独立地测试这样的模块,同时还要确保我的测试不会在Mongo中插入记录/文档.

I want to ensure I test such a module in isolation while also ensuring that my tests don't insert records/documents into Mongo.

是否存在可以使用代理require()的模块/程序包,以便可以注入自己的模拟程序?他人通常如何解决此问题?

Is there a module/package that I can use that proxies require() so I can inject in my own mocks? How do other's typically address this issue?

推荐答案

您可以使用类似 nCore

老实说,这其中的难点实际上是模拟出mongoDB API,它是复杂且非琐碎的.我估计要花大约一周的时间才能模拟出我使用的大多数mongo API,因此我只需再次测试计算机上的本地mongodb数据库(始终处于怪异状态)

To be honest, the hard part of this is actually mocking out the mongoDB API, which is complex and non trivial. I estimate it would take about a week to mock out most of the mongo API I use so I just test againts the a local mongodb database on my machine (which is always in a weird state)

然后使用nCore特定语法

Then with nCore specific syntax

// myModule.js
module.exports = {
  myMethod: function () { 
    this.mongo.doStuff(...)
  },
  expose: ["myMethod"]
};

// test-myModule.js
var module = require("myModule")

module.mongo = mongoMock
assert(module.myMethod() === ...)

这篇关于在Node中模拟依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆