Observable内部的角度单元测试EventEmitter



我正在尝试对一个名为insert(e)的函数进行单元测试,该函数接受一个事件并将上传的图像插入到应用程序的目录中。该函数解析事件以获取上传的文件,并使用Observable来发送数据。这是插入功能:

insert(e: Event) {
...
Observable.forkJoin(subjects$).subscribe(res => {
res = res.filter(g => g);
if (res.length) {
this.updateToolbox.emit({ add: res });
}
});
}

注意指的是处理subjects$解析和构建的代码

这是我的组件规范文件:

it('should insert into catalog', () => {
const updateToolboxSpy = spyOn(catalog.updateToolbox, 'emit');
let file = new File([''], 'testfile.svg', {type: 'image/svg+xml'});
file = new File([file.slice(0, file.size), '<svg xmlns="http://www.w3.org/2000/svg" '
+ 'xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Capa_1" x="0px" y="0px" '
+ 'width="100%" height="100%" viewBox="0 0 505.922 505.922" style="enable-background:new '
+ '0 0 505.922 505.922;" xml:space="preserve" preserveAspectRatio="none">↵<g>↵  <g>↵        '
+ '<path d="M442.68,31.622h-18.182C423.887,14.07,409.564,0,391.859,0c-17.699,0-32.02,14.07-32.631,31.622H63.24    '
+ 'c-26.193,0-47.43,21.236-47.43,47.43v379.44c0,26.193,21.236,47.43,47.43,47.43H442.68c26.195,0,47.432-21.236,47.432-47.43    '
+ 'V79.052C490.111,52.858,468.875,31.622,442.68,31.622z M67.757,106.158c0-12.473,10.11-22.583,22.583-22.583h72.277    '
+ 'c12.472,0,22.583,10.11,22.583,22.583s-10.11,22.583-22.583,22.583H90.34C77.874,128.74,67.757,118.63,67.757,106.158z     '
+ 'M252.96,449.459c-77.338,0-140.032-62.693-140.032-140.031c0-77.339,62.693-140.032,140.032-140.032    '
+ 's140.032,62.693,140.032,140.032C392.992,386.766,330.299,449.459,252.96,449.459z"/>↵      '
+ '<circle cx="252.96" cy="309.427" r="81.31"/>↵    </g>↵</g>↵<g>↵</g>↵<g>↵</g>↵<g>↵</g>↵<g>↵</g>↵<g>↵</g>↵<g>↵</g>↵<g>↵'
+ '</g>↵<g>↵</g>↵<g>↵</g>↵<g>↵</g>↵<g>↵</g>↵<g>↵</g>↵<g>↵</g>↵<g>↵</g>↵<g>↵</g>↵</svg>'], file.name);
const e: any = {
preventDefault: jasmine.createSpy('prevent'),
target: {
blur: jasmine.createSpy('blur'),
value: 'abc',
files: [file]
}
};
catalog.insert(e);
// getting called before the event gets emitted
// expect(updateToolboxSpy).toHaveBeenCalled();
/*Using setTimeout works */
setTimeout(function() {
expect(updateToolboxSpy).toHaveBeenCalled();
}, 5000);
});

上面的代码是有效的,但我不想使用setTimeout,也不想知道是否有angularjs或者jasmine的方法可以正确地期望调用EventEmitter。

是。Angular提供了一个async函数,该函数将消耗一个测试,并在完成测试之前等待任何异步操作完成。

import { async } from '@angular/core/testing'
...
describe('a test', async() => {
expect('some async thing').toWork();
});

还有其他处理异步测试的方法,Jasmine和其他Angular测试函数推荐了其中一些方法。查看此处的文档。

最新更新