我想为我的应用程序编写一些单元测试,我可以以某种方式" mock"与require一起使用的一些依赖项(' dependencyname')?
答案 0 :(得分:3)
You are looking for Proxyquire :)
//file1
var get = require('simple-get');
var assert = require('assert');
module.exports = function fetch (callback) {
get('https://api/users', callback);
};
//test file
var proxyquire = require('proxyquire');
var fakeResponse = {status:200};
var fetch = proxyquire('./get', {
'simple-get': function (url, callback) {
process.nextTick(function () {
callback(null, fakeResponse)
})
}
});
fetch(function (err, res) {
assert(res.statusCode, 200)
});
直接退出他们的文档。
答案 1 :(得分:0)
是的,例如jest => https://facebook.github.io/jest/
// require model to be mocked
const Mail = require('models/mail');
describe('test ', () => {
// mock send function
Mail.send = jest.fn(() => Promise.resolve());
// clear mock after each test
afterEach(() => Mail.send.mockClear());
// unmock function
afterAll(() => jest.unmock(Mail.send));
it('', () =>
somefunction().then(() => {
// catch params passed to Mail.send triggered by somefunction()
const param = Mail.send.mock.calls[0][0];
})
);
});