我想为接收ElementRef的方法编写一个测试。我没有办法嘲笑ElementRef,有人能帮上忙吗?非常感谢!
exampleService.service.ts:
export class exampleService {
exampleMethod(elRef: ElementRef): string {
const elWidth = elRef.nativeElement.offsetWidth;
return elWidth;
}
}
testfile.service.spec.ts:
describe('ExampleService', () => {
let service: ExampleService;
beforeEach(() => {
service = TestBed.inject(ExampleService);
});
it('How to mock the ELEMENTREF?', () => {
expect(service.exampleMethod(ELEMENTREF)).toBe('100');
});
});
发布于 2021-06-15 07:02:41
可以创建具有需要与ElementRef对象一起使用的属性和方法的对象:
const mockElementRef: any = {
nativeElement: {
offsetWidth: 100
}
};
beforeEach(async(() => TestBed.configureTestingModule({
imports: [ ... ],
declarations: [ Component ],
providers: [
{ provide: ElementRef, useValue: mockElementRef }
],
schemas: [ NO_ERRORS_SCHEMA ]
}).compileComponents()));
.......
it('How to mock the ELEMENTREF?', () => {
expect(service.exampleMethod(mockElementRef)).toBe('100');
});https://stackoverflow.com/questions/67981275
复制相似问题