Similar a unapregunta anterior , estoy tratando de simular una biblioteca externa usando sinon . Sin embargo, la biblioteca exporta dos funciones y un espacio de nombres con el mismo nombre FastGlob .
Tengo una comprensión básica de la sobrecarga de funciones, pero no estoy seguro de cómo funcionan los espacios de nombres con la sobrecarga de funciones o si este problema está relacionado.
Independientemente, quiero burlarme de la definición de la primera función, pero sinon está viendo el espacio de nombres
declare function FastGlob(source: PatternInternal | PatternInternal[], options: OptionsInternal & EntryObjectPredicate): Promise<EntryInternal[]>;Aquí está el archivo de definición de bibliotecas.
import { Options as OptionsInternal } from './settings'; import { Entry as EntryInternal, FileSystemAdapter as FileSystemAdapterInternal, Pattern as PatternInternal } from './types'; declare function FastGlob(source: PatternInternal | PatternInternal[], options: OptionsInternal & EntryObjectPredicate): Promise<EntryInternal[]>; declare function FastGlob(source: PatternInternal | PatternInternal[], options?: OptionsInternal): Promise<string[]>; declare namespace FastGlob { type Options = OptionsInternal; type Entry = EntryInternal; type Task = taskManager.Task; type Pattern = PatternInternal; type FileSystemAdapter = FileSystemAdapterInternal; function sync(source: PatternInternal | PatternInternal[], options: OptionsInternal & EntryObjectPredicate): EntryInternal[]; function sync(source: PatternInternal | PatternInternal[], options?: OptionsInternal): string[]; function stream(source: PatternInternal | PatternInternal[], options?: OptionsInternal): NodeJS.ReadableStream; function generateTasks(source: PatternInternal | PatternInternal[], options?: OptionsInternal): Task[]; function isDynamicPattern(source: PatternInternal, options?: OptionsInternal): boolean; function escapePath(source: PatternInternal): PatternInternal; } export = FastGlob;Intenté usar variaciones de la siguiente prueba, pero TS se queja de que solo puede encontrar las funciones dentro del espacio de nombres (sincronización, transmisión, etc.). Eliminar el nombre de la cadena de la función provoca un problema diferente.
import * as FastGlob from 'fast-glob'; import { stub, SinonStub } from "sinon"; import { Pattern, Entry, Options } from "fast-glob"; (stub(FastGlob, "FastGlob") as unknown as SinonStub<[s: Pattern | Pattern[], o: Options], Promise<Entry[]>>).resolves([{test: '/test/'} as unknown as Entry])El código de la aplicación se está utilizando así.
import * as glob from 'fast-glob'; const paths: Array<string> = await glob('./my/glob/**/*.ts', { absolute: true });Necesita un módulo adicional para stub fast-glob, debido a la forma en que se define. Para obtener más información, puede consultar este problema de sinon .
Puedo darle un ejemplo si puede usar un módulo adicional: proxyquire .
Tengo este glob.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 };Prueba usando el archivo de especificaciones:
// 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)); }) });Cuando lo ejecuta usando ts-mocha y nyc desde la terminal:
$ 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 | --------------|---------|----------|---------|---------|-------------------