【问题标题】:how to stub react-redux useReducer hook - using cypress如何存根 react-redux useReducer 钩子 - 使用 cypress
【发布时间】:2021-05-15 00:42:18
【问题描述】:

有人可以帮我理解如何从 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>
  );
};

【问题讨论】:

    标签: reactjs unit-testing cypress stubbing use-reducer


    【解决方案1】:

    万一其他人最终出现在这个线程中,我最终设法完成了这一切(在插件和一些 babel 配置更改的帮助下)。

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2019-11-11
      • 2021-05-27
      相关资源
      最近更新 更多