我正在使用 superagent在 React 应用程序中支持一些 XHR 服务。我已经围绕 superagent 编写了一个非常薄的包装器以使配置更容易。事实证明,尝试测试这一薄层非常令人头疼。
我知道有 issues使用 jest 和 node 核心依赖项,我可以通过 dontMock
ing superagent 的依赖项让事情正常进行。但我更愿意开个 Jest ,只是模拟 superagent
而不会默认爆炸。
结果是我的 package.json 中出现极其冗长的测试介绍或 unMockedModulePatterns
条目,是否有更好的方法?
// my-module.js
'use strict';
var request = require('superagent');
module.exports = function () {
return request.get('http://stackoverflow.com/questions/tagged/jestjs');
};
示例测试:
// __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');
});
});
最佳答案
我相信更好的方法是写manual mocks ,像这样:
__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');
};
jest 的自动模拟在工作时非常好,但在许多情况下,编写自己的模拟比尝试支持其自动模拟更容易。
关于node.js - 问题模拟 Node 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28257722/