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)';
})
})但是它并没有像预期的那样工作(不是存根...进行直接的实际呼叫)。请帮助我正确的存根和测试。
发布于 2018-11-05 14:39:17
默认情况下,file-type包导出功能,所以只用Sinon比较难模拟。我们必须让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')
});
});希望能有所帮助
https://stackoverflow.com/questions/53059762
复制相似问题