如何存根 react-redux useReducer 钩子 - 使用 cypress

IT技术 reactjs unit-testing cypress stubbing use-reducer
2021-05-10 10:57:14

有人可以帮助我了解如何从 react-redux 存根 useReducer 吗?这段代码看起来应该可以工作,但实际上并没有(存根从不拦截 useReducer 函数)。

import React from 'react';
import { mount } from '@cypress/react';
import * as ReactReduxModule from 'react-redux';
const { Provider } = ReactReduxModule;

import { Button } from './button';
import { store } from './store';
import * as SomethingModule from './something';

describe('<Button />', () => {
  it('uses stubbed things', () => {
    cy.stub(ReactReduxModule, 'useSelector')
      .as('useSelector')
      .returns({ moo: 'woof' });
    cy.stub(SomethingModule, 'something').as('something').returns('scary!!');

    cy.get('@something').should('not.have.been.called'); 
    cy.get('@useSelector').should('not.have.been.called'); 

    mount(
      <Provider store={store}>
        <Button />
      </Provider>,
    );
    // cy.contains('moo: woof scary').should('exist');
    cy.get('@something').should('have.been.called'); // passes
    cy.get('@useSelector').should('have.been.called'); // fails! :(
  });
});

“某物”存根确实触发并拦截了导入,但 useSelector 存根不会。:( 帮助 有问题的组件也超级简单:

import React from 'react';
import { useSelector } from 'react-redux';

import { something } from './something';
import { StoreState } from './store';

export const Button = ({}) => {
  const { moo } = useSelector((store: StoreState) => {
    return { moo: store.moo };
  });
  return (
    <button>
      moo: {moo} {something()}
    </button>
  );
};
1个回答

如果其他人最终出现在这个线程中,我最终设法做到了这一切(借助插件和一些 babel 配置更改)。

我刚刚在我的 babel 构建中添加了这个小插件:https : //github.com/asapach/babel-plugin-rewire-exports,它允许您重新连接module文件中包含的大多数*导入(假设您在 esmodule 代码库中工作) .

我在这里有一些演示代码:https : //github.com/glomotion/stripped-down-next-rewire-ts/blob/tryout/rewire-exports/src/components/Moo/Moo.cy.test.jsx

* 注意:模拟 npm 组件有点棘手,除非有问题的组件是一个 esmodule,在这种情况下,你配置 babel 来解析它,你很高兴!