Observable内部的角单元测试EventEmitter

时间:2018-07-23 14:44:34

标签: angular unit-testing jasmine observable

我正在尝试对名为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,想知道是否有 angular js 茉莉花< / em>正确预期EventEmitter被调用的方法。

1 个答案:

答案 0 :(得分:0)

是的。 Angular提供了一个docker run -itd -v "mylocalfolder":"myContainerFolder" container:name sh函数,该函数将消耗测试并等待任何异步操作完成才结束测试。

async

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