[英]How to (sinon) stub an external module function?
import fileType from 'file-type';
export function checkFileType(input){
if(fileType(input).mime === 'image/png'){
// do something;
return 'Yes It is PNG';
} else {
// do something;
return 'No. It is not PNG';
}
}
我想为上述方法编写单元测试用例,因为我想存根'fileType(input)'。
我尝试在测试文件中执行以下操作。
import * as fileTypeObj from 'file-type';
import sinon from 'sinon';
describe(__filename, () => {
let sandbox;
beforeEach(() => {
sandbox = sinon.sandbox.create();
});
afterEach(() => {
sandbox.restore();
});
it('test the function', async () => {
sandbox.stub(fileTypeObj, 'default').withArgs('someinput').returns({mime: 'image/png'});
await checkFileType('someinput)';
})
})
但是它没有按预期方式工作(不存根……直接拨打电话)。 请帮助我正确存根并进行测试。
file-type
包导出功能是默认设置,因此仅使用Sinon
很难模拟。 我们必须让proxyquire
参与proxyquire
,以proxyquire
测试。
这是使用proxyquire
的测试proxyquire
const chai = require('chai');
const sinon = require('sinon');
const proxyquire = require('proxyquire');
const expect = chai.expect;
describe('unit test', function() {
let fileTypeStub;
let src;
beforeEach(function() {
fileTypeStub = sinon.stub();
src = proxyquire('./path-to-your-src', { 'file-type': fileTypeStub });
});
afterEach(function() {
sinon.restore();
})
it('returns yes for PNG', async function() {
fileTypeStub.returns({ mime: 'image/png'});
const response = await src.checkFileType('any input');
expect(response).to.equal('Yes It is PNG')
});
it('returns no for not PNG', async function() {
fileTypeStub.returns({ mime: 'image/jpg'});
const response = await src.checkFileType('any input');
expect(response).to.equal('No. It is not PNG')
});
});
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.