如何监视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'.
这是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/