Angular 4使用窗口测试代码

Eug*_*Kim 1 testing window jasmine karma-jasmine angular

我想测试一个代码

public openAttachment(attachment: Attachment) {
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(attachment.getFile());
    }
    else {
        let objectUrl = URL.createObjectURL(attachment.getFile());
        window.open(objectUrl);
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道如何访问窗口或模拟窗口以对其进行测试。我是角度测试的新手,因此,如果您能详细解释一下,那就太好了!

Sid*_*era 7

您还可以window在测试中访问该对象。因此,您可以轻松地监视它们。

我已经创建了一个轻量级的组件,并考虑了您的特定用例。

以下是组件:

import { Component } from '@angular/core';

@Component({
  selector: 'app-attachment',
  templateUrl: './attachment.component.html',
  styleUrls: ['./attachment.component.css']
})
export class AttachmentComponent {

  public openAttachment(attachment) {
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(attachment.getFile());
    }
    else {
      let objectUrl = URL.createObjectURL(attachment.getFile());
      window.open(objectUrl);
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

请注意,在这里我不确定Attachment类型是什么。因此,我已经从openAttachment函数的参数中删除了该类型注释。

现在这就是我的测试的样子:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { AttachmentComponent } from './attachment.component';

describe('AttachmentComponent', () => {
  let component: AttachmentComponent;
  let fixture: ComponentFixture<AttachmentComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AttachmentComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AttachmentComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });

  describe('openAttachment', () => {
    let attachment;
    beforeEach(() => {
      attachment = { getFile: function() { return 'foo'; } };
    });

    it('should call `window.open` if `msSaveOrOpenBlob` is not a method present on the `window.navigator`', () => {

      // Since this will probably run on Chrome, Chrome Headless or PhantomJS, if won't have a `msSaveOrOpenBlob` method on it.
      // So this is the test for the else condition.
      let windowOpenSpy = spyOn(window, 'open');
      let returnValue = { foo: 'bar' };
      let urlCreateObjectSpy = spyOn(URL, 'createObjectURL').and.returnValue(returnValue);

      component.openAttachment(attachment);

      expect(urlCreateObjectSpy).toHaveBeenCalledWith('foo');
      expect(windowOpenSpy).toHaveBeenCalledWith(returnValue);

    });

    it('should call the `window.navigator.msSaveOrOpenBlob` if `msSaveOrOpenBlob` is present on the navigator object', () => {

      // To cover the if condition, we'll have to attach a `msSaveOrOpenBlob` method on the window.navigator object.
      // We can then spy on it and check whether that spy was called or not.
      // Our implementation will have to return a boolean because that's what is the return type of `msSaveOrOpenBlob`.
      window.navigator.msSaveOrOpenBlob = function() { return true; };
      let msSaveOrOpenBlobSpy = spyOn(window.navigator, 'msSaveOrOpenBlob');

      component.openAttachment(attachment);

      expect(msSaveOrOpenBlobSpy).toHaveBeenCalledWith('foo');

    });

  });

});
Run Code Online (Sandbox Code Playgroud)

我想再次强调一个事实,即我不确定附件的类型。因此,在beforeEach我的openAttachmentdescribe块中,我将其分配给一个对象,该对象包含一个以getFilevalue 命名的键,该键最终将返回一个string foo

同样,由于默认情况下您的测试将在Chrome中运行,因此您不会msSaveOrOpenBlobwindow.navigator对象上获得该功能。因此,openAttachmentdescribe块中的第一个测试将仅覆盖else块。

不过,在第二个测试中,我们已经msSaveOrOpenBlobwindow.navigator对象上添加了一个函数。因此,现在它可以覆盖if分支。因此,您可以在msSaveOrOpenBlob函数上创建一个间谍,expect这个间谍toHaveBeenCalledWithattachment.getFile()方法返回的任何内容(foo在这种情况下为字符串)

希望这可以帮助。