angular - 如何以 Angular 对剪贴板副本进行单元测试?

标签 angular jasmine spy

如何监视clipboard.copy 方法? 对于

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

我收到警告

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

这是CopyToClipboardHost

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

最佳答案

我不知道为什么它在你的案例中不起作用,但我设法创建了简单的测试案例并且它工作正常:

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

需要注意的一件事 - 不要将外部模块导入 TestingModule,因为您只想测试您的组件,而不是模拟/监视所需的依赖项。

关于angular - 如何以 Angular 对剪贴板副本进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69555648/

相关文章:

angular - 如何使用 Jasmine 单元测试测试私有(private)方法

javascript - restangular multiple promise Jasmine

c# - 适用于 Windows 8 的 spy 实用程序

node.js - 在从 Node 模块导出的函数上使用 `jest.spyOn`

Angular 8 ngrx存储如何在没有订阅回调的情况下获取reducer值?

angular - RxJS Observables,在发出 API 请求之前检查缓存

css - Angular 通用 : serving critical CSS and delaying non-critical

angular - NGX Cookie 服务不返回任何内容

javascript - Angular 1.6,$compileProvider 和测试

java - PowerMockito verifyTimes 始终传递私有(private)方法