How to unit test clipboard copy in angular?

Viewed 1227

How to spy on clipboard.copy method? For

const clipboard = TestBed.inject(Clipboard);
spyOn(clipboard, 'copy').and.returnValue(true);

I get warning that

Argument of type '"copy"' is not assignable to parameter of type 'keyof Clipboard'.

enter image description here

I've also tried to add this to imports and declarations: I've also tried to add this to imports and declarations

This is CopyToClipboardHost

class CopyToClipboardHost {
  public content = '';
  public attempts = 1;
  public copied = jasmine.createSpy('copied spy');
}
1 Answers

I don't know why it didn't work within your case but I manage to create simple test case and it's working properly:

import {Component} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {Clipboard} from '@angular/cdk/clipboard';
import createSpyObj = jasmine.createSpyObj;

@Component({
  selector: 'app-root',
  template: ''
})
export class SampleComponent {
  constructor(private clipboard: Clipboard) {
  }

  copySomething(): void {
    this.clipboard.copy('test');
  }
}

describe('SampleComponent', () => {
  let fixture: ComponentFixture<SampleComponent>;
  let component: SampleComponent;
  const clipboardSpy = createSpyObj<Clipboard>('Clipboard', ['copy']);

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [SampleComponent],
      providers: [{provide: Clipboard, useValue: clipboardSpy}]
    }).compileComponents();
  }));

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

  it('should call clipboard copy', () => {
    component.copySomething();

    expect(clipboardSpy.copy).toHaveBeenCalledWith('test');
  });
});

One thing to note - do not import external modules to TestingModule as you want to test only your component rather do mock/spy upon required dependencies.

Related