Angular - unit test spy无法识别该函数已被调用

时间:2017-07-31 13:43:49

标签: angular unit-testing typescript karma-jasmine angular-directive

我有一个用于测试指令的测试组件:

export class UnitTestComponent implements OnInit {
  @ViewChild(BackgroundLoadedDirective) backgroundLoaded: BackgroundLoadedDirective;

  public url = 'https://www.codeproject.com/KB/GDI-plus/ImageProcessing2/flip.jpg';

  constructor() {}

  ngOnInit() {}

  loaded(): void {
    console.log(true)
  }
}

然后我有这个指令,我想写一些测试:

@Directive({
  selector: '[backgroundLoaded]'
})

export class BackgroundLoadedDirective {
  @Input('backgroundLoaded') set url(value) {
    this.createImage(value);
  };

  get url() {
    return this._url;
  }

  @Output() loaded: EventEmitter<any> = new EventEmitter<any>();

  public img: HTMLImageElement;

  private _url: string;

  @HostBinding('class.background-loaded')
  isLoaded = false;

  createImage(url: string): void {

    // This gets logged as expected
    console.log(url);

    this._url = url;

    this.img = new Image();

    this.img.onload = () => {
      this.isLoaded = true;
      this.load.emit(url);
    };

    this.img.src = url;
  }
}

到目前为止,我刚刚接受了这个测试:

describe('BackgroundLoadedDirective', () => {

  let component: UnitTestComponent;
  let fixture: ComponentFixture<UnitTestComponent>;
  let spy: any;

  beforeEach(() => {

    TestBed.configureTestingModule({
      declarations: [
        UnitTestComponent,
        BackgroundLoadedDirective
      ],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [
        {provide: ComponentFixtureAutoDetect, useValue: true}
      ]
    });

    fixture = TestBed.createComponent(UnitTestComponent);
    component = fixture.componentInstance;
  });

  it('should create a fake img tag', () => {

    spy = spyOn(component.backgroundLoaded, 'createImage').and.callThrough();

    expect(component.backgroundLoaded.img).toBeTruthy();
    expect(spy).toHaveBeenCalled();
  });
});

问题是测试失败了:

Expected spy createImage to have been called.

尽管调用了函数,为什么没有间谍工作?

修改

只是为了澄清,这是测试组件的html,它应用了该指令并为其提供了网址。

<div [urlToBackground]="url" [backgroundLoaded]="url" (loaded)="loaded($event)"></div>

1 个答案:

答案 0 :(得分:2)

基本上干扰的是角度生命周期钩子。您的测试在时间方面并不够关注。

为了更容易测试,触发更改,然后测试你的setter是否正常工作(并调用你正在侦察的功能)。

这样的事情:

it('should create a fake img tag', () => {
    let spy: jasmine.Spy = spyOn(component.backgroundLoaded, 'createImage').and.callThrough();

    comp.backgroundLoaded.url = 'foobar';
    fixture.detectChanges(); // wait for the change detection to kick in

    expect(spy).toHaveBeenCalled();
});

希望它有所帮助。

(编辑:为detectChanges()删除了一个ngOnInit,因为此处不需要它,应该在测试之前调用它)