如何模拟传递给方法的 ElementRef
How to mock an ElementRef that is passed into a method
我想为接收 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');
});
});
您可以使用需要与 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');
});
我想为接收 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');
});
});
您可以使用需要与 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');
});