gpt4 book ai didi

angular - 如何模拟传递给方法的 ElementRef

转载 作者:行者123 更新时间:2023-12-05 04:48:38 26 4
gpt4 key购买 nike

我想为接收 ElementRef 的方法编写测试。我找不到模拟 ElementRef 的方法,有人可以帮忙吗?非常感谢!

示例服务.service.ts:

export class exampleService {
exampleMethod(elRef: ElementRef): string {
const elWidth = elRef.nativeElement.offsetWidth;
return elWidth;
}
}

测试文件.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');
});

关于angular - 如何模拟传递给方法的 ElementRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67981275/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com