您需要额外的模块来存根fast glob,因为它的定义方式不同。欲知更多信息,你可以看看这个
sinon issue
.
如果你可以使用其他模块,我可以给你举个例子:
proxyquire
.
我有这个球。ts。
// File: glob.ts
import glob from 'fast-glob';
async function getPaths(input: string): Promise<Array<glob.Entry|string>> {
return glob(input, { absolute: true });
}
export { getPaths };
使用规范文件进行测试:
// File: glob.spec.ts
import * as FastGlob from 'fast-glob';
import sinon from 'sinon';
import proxyquire from 'proxyquire';
import { expect } from 'chai';
describe('Glob', () => {
const fakeInput = './node_modules/**/settings.js';
it('getPaths using first fast-glob definition', async () => {
const fakeResult = [{ test: '/test/' } as unknown as FastGlob.Entry];
const fakeFunc = sinon.fake.resolves(fakeResult);
// Create stub using proxyquire.
const glob = proxyquire('./glob', {
'fast-glob': sinon.fake.resolves(fakeResult),
});
const paths = await glob.getPaths(fakeInput);
expect(paths).to.deep.equal(fakeResult);
expect(fakeFunc.calledOnceWithExactly(fakeInput));
})
it('getPaths using second fast-glob definition', async () => {
const fakeResult = ['/test/'];
const fakeFunc = sinon.fake.resolves(fakeResult);
// Create stub using proxyquire.
const glob = proxyquire('./glob', {
'fast-glob': sinon.fake.resolves(fakeResult),
});
const paths = await glob.getPaths(fakeInput);
expect(paths).to.deep.equal(fakeResult);
expect(fakeFunc.calledOnceWithExactly(fakeInput));
})
});
当您从终端使用ts mocha和nyc运行时:
$ npx nyc ts-mocha glob.spec.ts
Glob
â getPaths using first fast-glob definition (137ms)
â getPaths using second fast-glob definition
2 passing (148ms)
--------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
glob.spec.ts | 100 | 100 | 100 | 100 |
glob.ts | 100 | 100 | 100 | 100 |
--------------|---------|----------|---------|---------|-------------------