如何在Cypress测试中获取NGRX Store状态?
在Cypress中获取NGRX Store状态的正确方式
NGRX Store是基于RxJS的Observable实现,和Redux原生Store的API不同,没有同步的getState()方法,这就是你调用失败的核心原因。下面是几种可行的调整方案:
1. 直接通过subscribe获取完整状态
利用RxJS的subscribe方法订阅Store,获取当前状态:
cy.window().its('store').then(store => { store.select(state => state).subscribe(entireState => { // 将状态存入Cypress别名,方便后续使用 cy.wrap(entireState).as('fullStoreState'); // 直接进行断言 expect(entireState.migrations).to.have.property('isCompleted', true); }); });
2. 获取特定状态切片
如果只需要Store中的某一部分状态,可以直接传入对应的选择器:
cy.window().its('store').then(store => { // 订阅migrations切片的状态 store.select('migrations').subscribe(migrationsState => { cy.wrap(migrationsState).should('deep.equal', { isCompleted: true, migrationList: [] }); }); });
3. 封装成Cypress自定义命令(推荐)
为了提升复用性,可以将获取状态的逻辑封装成自定义命令,在cypress/support/commands.js中添加:
Cypress.Commands.add('getNgrxState', (selector = state => state) => { return cy.window().its('store').then(store => { return new Cypress.Promise(resolve => { const subscription = store.select(selector).subscribe(state => { resolve(state); subscription.unsubscribe(); // 拿到状态后取消订阅,避免内存泄漏 }); }); }); });
之后在测试用例中直接调用:
// 获取完整状态 cy.getNgrxState().then(state => { expect(state.migrations.isCompleted).to.be.true; }); // 获取指定切片 cy.getNgrxState('migrations').then(migrationsState => { expect(migrationsState.migrationList).to.have.length(0); });
注意事项
- NGRX状态是异步流,必须通过
subscribe或Promise包裹,确保Cypress等待状态获取完成后再执行后续逻辑。 - 获取状态后记得取消订阅,避免不必要的内存占用。
内容的提问来源于stack exchange,提问作者Tom Carmi
相关产品推荐
相关产品推荐

