问题描述
我正在使用 @cypress/react
包对 React 组件执行单元测试。
就我而言,这些 React 组件包含外部影响,例如服务或 Redux 状态管理。
我尝试使用 cy.stub()
对这些外部组件进行存根,但出现错误,我不知道如何解决。
示例:
我有一个组件从 redux 调用 useSelector
以获取当前状态 currentState
。如下所示:
import { currentStateSelector } from 'store/current-state/selectors';
export default function MyComponent() {
const currentState = useSelector(currentStateSelector);
return (
currentState !== null ?
<div data-testid='my-component'>
{ currentState.name }
</div>
:
<></>
);
}
为了测试这一点,我创建了以下规范文件:
import React from 'react';
import mount from '@cypress/react/dist';
import MyComponent from './my-component';
import * as reactRedux from 'react-redux';
import { store } from '../../store';
describe('MyComponent',() => {
it('renders',() => {
const useSelectorMock = cy.stub(reactRedux,'useSelector');
const currentState = {
name: 'test',};
useSelectorMock.returns(currentState);
mount(
<reactRedux.Provider store={store}>
<MyComponent/>
</reactRedux.Provider>
);
cy.get('[data-testid=my-component]').should('exist');
});
});
使用 npx cypress open
运行测试它给了我一个断言错误:
Timed out retrying after 4000ms: Expected to find element: [data-testid=my-component],but never found it.
显然,我尝试存根的元素返回了一个空值,这就是发生此 AssertionError 的原因。但是我该如何解决这个问题?
也许我还没有完全理解存根功能,但经过几天的研究,我没有发现任何有用的东西。任何帮助将不胜感激。
更新
我切换到测试框架 jest 并且通过在 describe(...)
之前编写以下内容来模拟工作:
jest.mock('react-redux',() => ({
useSelector: jest.fn( () => { return 'desired return-object' })
}));
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)