Tengo este tipo de código:
componente.ts
async ngOnInit() { import('dom-to-image').then(module => { const domToImage = module.default; const node = document.getElementById('some-id'); domToImage.toPng(node).then(dataUrl => { // The test is not getting over here }).catch(() => {}); }); }componente.spec.ts
describe('SomeComponent', () => { beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ .... }).compileComponents(); fixture = TestBed.createComponent(SomeComponent); component = fixture.componentInstance; fixture.detectChanges(); }) ) it('should create', async () => { expect(component).toBeTruthy(); }); }Entonces la pregunta es, ¿cómo me burlo de esta promesa domToImage.toPng? ¿Hay alguna solución para que la prueba pueda continuar su ejecución y resolver la promesa?
Gracias de antemano isma
Tienes que simular module.default:
module.default = { toPng: () => new Promise((resolve, reject) => {resolve('myExpectedResponseData')}) };Y un rechazo de llamada simulado en las pruebas de error. Nota: si no puede simular module.default directamente, intente spyOnProperty
Recuerdo que tuve un problema similar y no pude espiar la import para burlarme de ella.
Lo que hice para hacer feliz a la prueba fue moverla a su propio método y espiar ese método.
async ngOnInit() { importDomToImage().then(module => { const domToImage = module.default; const node = document.getElementById('some-id'); domToImage.toPng(node).then(dataUrl => { // The test is not getting over here }).catch(() => {}); }); } importDomToImage(): Promise<any> { // can make any more specific return import('dom-to-image'); } El primer fixture.detectChanges() es cuando se llama a ngOnInit() , por lo que tenemos que simular antes de eso.
describe('SomeComponent', () => { beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ .... }).compileComponents(); fixture = TestBed.createComponent(SomeComponent); component = fixture.componentInstance; // mock here spyOn(component, 'importDomToImage').and.returnValue(Promise.resolve({ default: { toPng: (arg) => Promise.resolve('abc'), // dataUrl will be abc } })); fixture.detectChanges(); }) ) it('should create', async () => { // await fixture.whenStable() to resolve all promises await fixture.whenStable(); expect(component).toBeTruthy(); }); }Con suerte, lo anterior debería funcionar y ayudarlo a comenzar.