嘲笑节点模块

我正在使用superagent在反应应用程序中支持一些XHR服务。 我在superagent上写了一个很薄的包装器,使configuration更容易。 试图testing这个薄层已被certificate是相当头痛的。

我知道,有jest和节点核心依赖的问题,我可以通过dontMock superagent的依赖项来工作。 但是我更喜欢在没有默认的情况下嘲笑superagent

结果是在我的package.json中有一个非常详细的testing介绍或unMockedModulePatterns入口,有没有更好的方法?

 // my-module.js 'use strict'; var request = require('superagent'); module.exports = function () { return request.get('http://stackoverflow.com/questions/tagged/jestjs'); }; 

一个示例testing:

 // __tests__/my-module-test.js 'use strict'; jest.dontMock('../'); // T_T jest.dontMock('superagent'); jest.dontMock('debug'); jest.dontMock('tty'); jest.dontMock('util'); jest.dontMock('stream'); jest.dontMock('fs'); jest.dontMock('delayed-stream'); jest.dontMock('mime'); jest.dontMock('path'); describe('mymodule', function () { var myModule, request; beforeEach(function () { myModule = require('../'); request = require('superagent'); request.get = jest.genMockFunction(function () { return { get: jest.genMockFunction() } }) }); it('makes an xhr request using superagent', function() { var req = myModule(); expect(request.get).toBeCalledWith('http://stackoverflow.com/questions/tagged/jestjs'); }); }); 

我相信更好的方法是写手动模拟 ,就像这样:

__tests __ / codeundertest.js:

 jest.dontMock('../codeundertest'); describe('whatever', function() { it('should do the do', function() { var request = require('superagent'); require('../codeundertest')(); expect(request.get.mock.calls[0][0]).toBe('http://stackoverflow.com/questions/tagged/jestjs'); }); }); 

__mocks __ / superagent.js:

 module.exports = { get: jest.genMockFunction() }; 

codeundertest.js:

 var request = require('superagent'); module.exports = function () { return request.get('http://stackoverflow.com/questions/tagged/jestjs'); }; 

笑话的自动嘲笑是非常好的时候,但有很多情况下,它会更容易写自己的嘲笑比试图支持automocking。