如何存根 react-redux useReducer 钩子 - 使用 cypress [英] how to stub react-redux useReducer hook - using cypress
问题描述
有人可以帮我理解如何从 react-redux 存根 useReducer 吗?这段代码看起来应该可以工作,但实际上并没有(存根从不拦截 useReducer 函数).
could someone please help me understand how to stub useReducer from react-redux? This code looks like it should work, but it just doesnt (stub never intercepts the useReducer function).
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! :(
});
});
某物"stub 确实会触发和拦截导入,但 useSelector stub 不会.:(帮助有问题的组件也非常简单:
the "something" stub does indeed trigger and intercept the import, but the useSelector stub does not. :( help the component in question is SUPER simple too:
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>
);
};
推荐答案
万一其他人最终出现在这个线程中,我最终设法做到了这一切(借助插件和一些 babel 配置更改).
Incase anyone else ever ends up in this thread, I eventually managed to do all this (with the help of a plugin and some babel config changes).
>
我刚刚在我的 babel 构建中添加了这个小插件:https://github.com/asapach/babel-plugin-rewire-exports 允许您重新连接包含在模块文件中的大多数*导入(假设您在 esmodule 代码库中工作).
I just added this little plugin into my babel build: https://github.com/asapach/babel-plugin-rewire-exports which allows you to rewire most* imports contained inside a module file (presuming ur working inside an esmodule codebase).
I've got some demo code here: https://github.com/glomotion/stripped-down-next-rewire-ts/blob/tryout/rewire-exports/src/components/Moo/Moo.cy.test.jsx
*
注意:模拟 npm 组件有点棘手,除非有问题的组件是一个 esmodule,在这种情况下,你配置 babel 来解析它,你很高兴!
*
note: To mock npm components is a little trickier, unless the component in question is an esmodule, in which case you configure babel to parse it, and ur good to go!
这篇关于如何存根 react-redux useReducer 钩子 - 使用 cypress的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!