[英]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';
}
}
I want to write unit test case for the above method, in that I want to stub 'fileType(input)'. 我想为上述方法编写单元测试用例,因为我想存根'fileType(input)'。
I have tried to do like below in my test file. 我尝试在测试文件中执行以下操作。
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)';
})
})
But it is not working as expected (Not stubbing ... making the direct actual call). 但是它没有按预期方式工作(不存根……直接拨打电话)。 Please help me to stub properly and test.
请帮助我正确存根并进行测试。
file-type
package export function as default, so it is a bit harder to mock with just Sinon
. file-type
包导出功能是默认设置,因此仅使用Sinon
很难模拟。 We must involve proxyquire
to make the testing easier. 我们必须让
proxyquire
参与proxyquire
,以proxyquire
测试。
This is how the test looks like using 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')
});
});
Hope it helps 希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.