-6ren">
gpt4 book ai didi

angular - ActivatedRoute Angular 7 的 Jasmine 测试

转载 作者:行者123 更新时间:2023-12-03 22:05:34 25 4
gpt4 key购买 nike

我正在尝试为 ActivatedRoute 编写一个简单的测试.这是我的测试的样子。

it("should check if subscribes are called in init", () => {
const subRouteSpy = spyOn(activatedRouteStub.paramMap, "subscribe");
component.ngOnInit();
expect(subRouteSpy).toHaveBeenCalled();
});

我的 TestBed config :
const activatedRouteStub = {
paramMap: {
subscribe() {
return of();
}
}
};

TestBed.configureTestingModule({
declarations: [HomeFilterDrawerComponent],
providers: [
{ provide: ActivatedRoute, useValue: activatedRouteStub }
],
imports: [
FormsModule,
StoreModule.forRoot(appReducers),
HttpClientTestingModule,
RouterTestingModule
]
}).compileComponents();

测试一直失败给我 Expected spy subscribe to have been called.不确定我在这里做错了什么。

里面的代码 ngOnInit组件的。
this.route.paramMap.subscribe(params => {
if (params["params"].slug !== undefined) {
}
});

最佳答案

Angular 正在克隆您的 activatedRouteStub当您通过 useValue 提供对象时.因此,您正在监视原始 stub 对象,但您的组件会看到一个没有附加 spy 的克隆对象。

这是 mentioned in the guide

Always get the service from an injector Do not reference the userServiceStub object that's provided to the testing module in the body of your test. It does not work! The userService instance injected into the component is a completely different object, a clone of the provided userServiceStub.



要解决此问题,您需要使用 TestBed.get 获取对克隆对象的引用。
let activatedRoute;

const activatedRouteStub = {
paramMap: {
subscribe() {
return of();
}
}
};

TestBed.configureTestingModule({
declarations: [HomeFilterDrawerComponent],
providers: [
{ provide: ActivatedRoute, useValue: activatedRouteStub }
],
imports: [
FormsModule,
StoreModule.forRoot(appReducers),
HttpClientTestingModule,
RouterTestingModule
]
}).compileComponents();

beforeEach(() => {
fixture = TestBed.createComponent(NewsComponent);
component = fixture.componentInstance;

// Get a reference to the injected value
activatedRoute = TestBed.get(ActivatedRoute);
});

it("should check if subscribes are called in init", () => {
// Spy on the injected value
const subRouteSpy = spyOn(activatedRoute.paramMap, "subscribe");
component.ngOnInit();
expect(subRouteSpy).toHaveBeenCalled();
});

或者,您可以保持代码不变,但更改 useValueuseFactory .这将允许您绕过克隆行为:
providers: [{ provide: ActivatedRoute, useFactory: () => activatedRouteStub }]

关于angular - ActivatedRoute Angular 7 的 Jasmine 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57497938/

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