gpt4 book ai didi

angular - 如何对 () => void 类型的变量进行单元测试

转载 作者:太空狗 更新时间:2023-10-29 18:35:18 24 4
gpt4 key购买 nike

我正在尝试为使用 MediaQueryList 的组件编写单元测试。我正在努力覆盖一行,它将箭头函数分配给一个变量。

我试过监视函数内部的方法,但我得到一个错误,指出该方法从未被调用过。

我的类(class):

export class AppComponent implements OnDestroy {
mobileQuery: MediaQueryList;
_mobileQueryListener: () => void;

constructor(
private changeDetectorRef: ChangeDetectorRef,
private media: MediaMatcher
) {
this.mobileQuery = this.media.matchMedia('(max-width: 1000px)');
this._mobileQueryListener = () => this.changeDetectorRef.detectChanges();
this.mobileQuery.addListener(this._mobileQueryListener);
}

ngOnDestroy(): void {
this.mobileQuery.removeListener(this._mobileQueryListener);
}
}

我的测试:

it('should setup the media query', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;

expect(app.mobileQuery).toBeTruthy();
expect(app._mobileQueryListener).toEqual(/* ??? */);
});

我想实现 100% 的代码覆盖率,为此,我需要覆盖 _mobileQueryListener 的分配。有什么想法吗?

最佳答案

我认为你应该尝试检查:

it('should setup the media query', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;

expect(app.mobileQuery).toBeTruthy();
expect(app._mobileQueryListener).toBeDefined();
});

_mobileQueryListener: () => void; 只是变量的声明而不是初始化。因此,检查它是否已定义。

并验证 _mobileQueryListener 调用 detectChanges() 的行为,您可以添加另一个测试用例(确保有 public changeDetectorRef将 spy 放在它上面):

it('should should call "detectChanges()" from "_mobileQueryListener"', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app._mobileQueryListener).toBeDefined();
spyOn(app.changeDetectorRef,"detectChanges").and.callThrough();
app._mobileQueryListener();
expect(app.changeDetectorRef.detectChanges).toHaveBeenCalled();
});

旁注,将下面的代码移至 beforeEach() block ,并全局声明这些变量

  fixture = TestBed.createComponent(AppComponent);
app = fixture.componentInstance;

关于angular - 如何对 () => void 类型的变量进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57064384/

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