CypressError: Timed out retrying: cy.its() errored because the property: 'store' does not exist on your subject

CypressError: Timed out retrying: cy.its() errored because the property: 'store' does not exist on your subject

我在测试我的应用程序时在 cypress 上遇到以下错误:

CypressError:重试超时:cy.its() 错误,因为 属性:'store' 在您的主题中不存在。

这是断掉的测试线:

cy.window().its('store').invoke('getState').then((state) => {
      expect(state.token).to.equal(tokenResponseMock.token);
    });

在我的代码中,一切正常,我在商店中获取了所有数据,没有问题,但由于未找到 'store',因此未通过测试。我想知道如果它按预期工作,为什么我会收到存储错误。我不知道发生了什么。谁能告诉我如何解决这个错误?

Login.js - 派发到商店的函数

  async function handleClick() {
    const { dispatchToken } = props;
    const tokenInfo = await fetchToken();
    localStorage.setItem('token', JSON.stringify(tokenInfo.token));
    dispatchToken(tokenInfo.token);
    history.push('/game');
  }

刚知道是怎么回事。 使用cypress进行测试时,需要在store文件中添加如下代码才能生效:

if (window.Cypress) {
  window.store = store;
}

不要混淆 localStorage 和 React store,它们是两个不同的东西。

localStorage

cy.get(somthing).click()
  .should(() => {
    const token = localStorage.getItem('token')
    expect(token).to.equal(tokenResponseMock.token)
  })

React 存储

在 React 应用中,将存储添加到 Cypress 对象

// init store
if (window.Cypress) {
  window.Cypress.store = store  // add to Cypress not window in case of conflict
}

测试中

cy.get(somthing).click()
  .should(() => {
    Cypress.store.getState().then(state => {
      expect(state.token).to.equal(tokenResponseMock.token)
    })
  })