如何在角度6单元测试中验证ngCopy方法调用

问题描述 投票:1回答:1

我正在使用ngCopy模块将文本复制到我的一个角度组件中的剪贴板

import {Component, Input, OnInit} from '@angular/core';
import {ngCopy} from 'angular-6-clipboard';

@Component({
  selector: 'app-error-message',
  templateUrl: './error-message.component.html',
  styleUrls: ['./error-message.component.scss']
})
export class ErrorMessageComponent implements OnInit {
  constructor() {
  }

  ngOnInit() {
  }

  copyMessage() {
    ngCopy('message');
  }

}

下面是该组件的spec文件

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

import {ErrorMessageComponent} from './error-message.component';

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

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

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

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

  it('should verify ngCopy', () => {
    const errorMessageComponent = TestBed.createComponent(ErrorMessageComponent).debugElement.componentInstance;
    errorMessageComponent.copyMessage();
    //Verify ngCopy Method call
  });

});

我目前正在使用ts-mockito框架,但无法弄清楚如何模拟ngCopy模块

如何在单元测试中使用'message'作为参数验证ngCopy方法调用?

angular karma-jasmine angular6 angular-unit-test
1个回答
1
投票

好的,你可以使用spyOn来做到这一点

spec.ts文件

import * as ngClipBoard from 'angular-6-clipboard';    // get alias to your library

................

it('should verify ngCopy', () => {
    const errorMessageComponent = TestBed.createComponent(ErrorMessageComponent).debugElement.componentInstance;

    let spy = spyOn(ngClipBoard,'ngCopy');    // create spy here

    errorMessageComponent.copyMessage();    // invoke method

    //Verify ngCopy Method call along with its parameter value
    expect(spy).toHaveBeenCalledWith('message');
});
© www.soinside.com 2019 - 2024. All rights reserved.