如何在 cypress 测试中 expose/access 像 Redux 这样的数据存储?

How to expose/access a data store like Redux within a cypress test?

Cypress docs 说可以

Expose data stores (like in Redux) so you can programmatically alter the state of your application directly from your test code.

我还观看了 Kent C. Dodds 先生的测试课程,他提到可以使用 Cypress 中的现有数据初始化 redux 存储(在测试之前或测试中,不确定)

我浏览了几乎所有的文档并进行了谷歌搜索,除了在介绍页面上被提及为主要区别之一之外,我找不到任何实际执行此操作的参考或示例。

如果可能的话,如何实现这样的目标?

我感兴趣的案例是E2E测试:

这可能不是最好的用例(甚至不是一个好的用例),但我敢肯定还有其他情况,至少用一些数据初始化你的 redux 状态会非常方便。

谢谢!

我不确定 React 应用程序的确切语法,但请参阅此博客 Testing Vue web applications with Vuex data store & REST backend

Vuex 相当于 Redux 的 VueJs。总而言之,您在应用程序启动的某个时刻添加了对商店的引用(代码片段从博客中修改为更通用)

if (window.Cypress) {
  // only available during E2E tests
  window.appStore = app.store  // Substitute an appropriate expression for React Redux
}

并像这样在测试中引用它

const getStore = () => cy.window().its('appStore')

it('has loading, newTodo and todos properties', () => {
  getStore().its('state').should('have.keys', ['loading', 'newTodo', 'todos'])
})

根据关于 Vuex 的回答,我这样做了,效果很好:

// after createStore(...)
if (window.Cypress) {
  window.__store__ = store;
}

// in cypress tests
cy.window().should('have.property', '__store__');
cy.window().its('__store__')
  .then(
    store => store.dispatch({ type: 'UPDATE_CURRENT_PROFILE' })
  );

不要忘记 cy.visit('anyRoute') 在对商店进行任何操作之前,以便在您尝试访问它时启动 React 应用程序并且已经创建了 redux 商店。

除了上述答案之外,您应该首先检查您在 store.js 文件中创建的 _store_ 实例是否附加了 window。就我而言,我做了如下操作:

const store = createStore(rootReducer,getCombinedStore(preloadedState),enhancer);
 if (global.window && global.window.Cypress) {
  global.window.__store__ = store;
  }

如您所见,在创建商店对象后,我还必须将其附加到 window。