1

I am using ngCopy module for copying text to clipboard in one of my angular componet

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');
  }

}

Below is the spec file for this component

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
  });

});

I'm currently using ts-mockito framework but couldn't figure out how to mock ngCopy module

How do I verify ngCopy method call with 'message' as argument in my unit test?

4

1 回答 1

1

Ok, you can do this using spyOn

spec.ts file

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');
});
于 2018-08-31T09:52:12.353 回答