我在 Angular 17 应用程序中遇到 Cypress v13.6.5 组件测试问题。之前通过的测试现在失败并出现以下错误:
The following error originated from your test code, not from Cypress.
> Cannot read properties of undefined (reading 'EventService')
...
Cypress could not associate this error to any specific test.
We dynamically generated a new test to display this failure.
at Module.EventService (
堆栈跟踪:
at Module.EventService (http://localhost:8080/__cypress/src/default-projects_libs_shared_data-access_src_index_ts-node_modules_css-loader_dist_runtime_ap-a65d0c.js:2711:128)
at 99574 (http://localhost:8080/__cypress/src/default-projects_libs_shared_data-access_src_index_ts-node_modules_css-loader_dist_runtime_ap-a65d0c.js:87:78)
at __webpack_require__ (http://localhost:8080/__cypress/src/runtime.js:23:42)
at 13530 (http://localhost:8080/__cypress/src/default-projects_libs_shared_data-access_src_index_ts-node_modules_css-loader_dist_runtime_ap-a65d0c.js:29:84)
at __webpack_require__ (http://localhost:8080/__cypress/src/runtime.js:23:42)
at 35845 (http://localhost:8080/__cypress/src/default-projects_libs_shared_data-access_src_index_ts-node_modules_css-loader_dist_runtime_ap-a65d0c.js:4829:77)
at __webpack_require__ (http://localhost:8080/__cypress/src/runtime.js:23:42)
at 57649 (http://localhost:8080/__cypress/src/default-projects_libs_shared_data-access_src_index_ts-node_modules_css-loader_dist_runtime_ap-a65d0c.js:4390:94)
at __webpack_require__ (http://localhost:8080/__cypress/src/runtime.js:23:42)
at 27430 (http://localhost:8080/__cypress/src/default-projects_libs_shared_data-access_src_index_ts-node_modules_css-loader_dist_runtime_ap-a65d0c.js:4510:94)
测试设置:
describe(ArrowSnapshotComponent.name, () => {
beforeEach(() => {
TestBed.overrideComponent(ArrowSnapshotComponent, {
add: {
imports: [ArrowSnapshotModule],
providers: [
{ provide: DASHBOARD_TOKEN, useClass: DashboardService },
{ provide: EVENT_SERVICE_TOKEN, useClass: EventService },
],
},
});
});
it('renders', () => {
cy.mount(ArrowSnapshotComponent, {
componentProperties: {
id: 0,
width: 0,
height: 0,
parentId: '',
slot: '',
refresh: 0,
},
});
});
});
其他背景:
采取的步骤:
我从失败的组件和测试中删除了所有依赖项,但它仍然失败。
尝试使用 TestBed.resetTestingModule() 在测试之间重置 Angular TestBed。
检查测试之间是否存在任何共享状态或副作用。
我尝试使用 useValue 而不是 useClass 来定义提供程序,但它不起作用。 问题:
如何解决 Cypress 组件测试中的“无法读取未定义的属性(读取‘EventService’)”错误?
我应该采取哪些步骤来确保EventService在测试环境中正确提供并可访问?
EventService的实现超级简单:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class EventService {
public cache: Map<string, BehaviorSubject<any>> = new Map<string, BehaviorSubject<any>>();
public get<T>(key: string): BehaviorSubject<T> {
...
}
onDestroy() {
...
}
}
它是通过注入令牌导入的:
@Inject(EVENT_SERVICE_TOKEN) private eventService: EventService,
所以我找到了解决办法。我查看了 cypress 在 devTools 中产生的错误。它给了我 cypress runner 中失败的线路和一些上下文线索。上下文线索指向我的库的index.ts 文件,这是我导出EventService 的位置。我将导出移至文件顶部并修复了它。这真的很奇怪。文件中导出的位置不应该影响它,但我们在这里。