在以下组件中,当isHybrid
道具为true时,我将对dom隐藏<HeaderContainer />
:
{...}
import { initializeRoutes, lazy } from 'hooks/useRouteHook';
import { isHybridSelector } from 'store/selectors';
import HeaderContainer from './header';
const routes = [
{ component: lazy(...component) },
{...}
];
export const UpgradeBlock = ({ isHybrid }) => {
return (
<Fragment>
{!isHybrid && (
<HeaderContainer />
)}
<div
>
<Suspense fallback={<Loader />}>{initializeRoutes(routes)}</Suspense>
</div>
</Fragment>
);
};
const mapStateToProps = state => ({
isHybrid: isHybridSelector(state),
});
CashUpgradeBlock.propTypes = {
isHybrid: PropTypes.bool,
}
export default connect(mapStateToProps)(UpgradeBlock);
在这里,我想通过模拟isHybrid
的prop值来检查<HeaderContainer />
组件的存在。
import React from 'react';
import { Router } from 'react-router-dom';
import { mount } from 'enzyme';
//Internal MockProvider Component.
import { MockProvider } from 'utils/tests';
import HeaderContainer from './header';
import UpgradeBlock from './index';
//Mock router-dom
jest.mock('react-router-dom', () => {
// Require the original module to not be mocked...
const originalModule = jest.requireActual('react-router-dom');
return {
__esModule: true, // Use it when dealing with esModules
...originalModule,
Redirect: jest.fn().mockReturnValue(<div>Redirect</div>),
};
});
//Mock selectors
jest.mock('store/selectors', () => ({
...jest.requireActual('store/selectors'),
isHybridSelector: jest.fn(),
}));
function UpgradeBlockWithStore({ history, ...props } = {}) {
return mount(
<Router {...}>
<MockProvider
{...props}
{...}
>
<UpgradeBlock {...props} />
</MockProvider>
</Router>
);
}
describe('CashUpgradeBlock', () => {
it('renders CashUpgradeBlock', () => {
const wrapper = UpgradeBlockWithStore();
const headerContainer = wrapper.find(HeaderContainer);
isHybridSelector.mockImplementation(() => false);
//Since isHybrid is set to false HeaderContainer should be present in the dom.
expect(headerContainer.exists()).toBe(true); //or .toBeTruthy()
})
})
控制台上console.log(wrapper.debug(((的结果如下:
console.log organisms/upgrade-block/upgrade-block.spec.js:57
<Router history={{...}}>
<MockProvider resources={{...}}>
<Provider store={{...}}>
<Connect(UpgradeBlock) history={{...}} location={{...}} resources={{...}} />
</Provider>
</MockProvider>
</Router>
即使在互联网上搜索了几个小时,我也找不到任何解决方案。。。我也不是测试专家;尽管在redux中isHybrid
默认设置为false
,但我也尝试过通过({isHybrid: false})
将其提供给UpgradeBlockWithStore(props)
,但仍然没有帮助,测试用例在dom树中找不到headerContainer
,并期望它是伪造的。
我的测试策略:
- 创建一个mock redux存储,而不是mock选择器
- 创建内存历史记录或使用
MemoryRouter
而不是嘲笑react-router-dom
我添加了您的代码并删除了不相关的部分。
例如
index.jsx
:
import React, { Fragment } from 'react';
import { connect } from 'react-redux';
import HeaderContainer from './header';
import { isHybridSelector } from './selectors';
export const UpgradeBlock = ({ isHybrid }) => {
console.log('isHybrid: ', isHybrid);
return <Fragment>{!isHybrid && <HeaderContainer />}</Fragment>;
};
const mapStateToProps = (state) => ({
isHybrid: isHybridSelector(state),
});
export default connect(mapStateToProps)(UpgradeBlock);
header.jsx
:
import React from 'react';
export default function Header() {
return <div>Header</div>;
}
selectors.js
:
const { createSelector } = require('reselect');
const selectEnvironment = (state) => state.environment;
export const isHybridSelector = createSelector(selectEnvironment, (environment) => environment.isHybrid);
index.test.jsx
:
import React from 'react';
import { Router } from 'react-router-dom';
import { Provider } from 'react-redux';
import { mount } from 'enzyme';
import { createMemoryHistory } from 'history';
import { createStore } from 'redux';
import HeaderContainer from './header';
import UpgradeBlock from './';
const rootReducer = (state = { environment: { isHybrid: false } }) => state;
const store = createStore(rootReducer);
const MockProvider = ({ children }) => {
return <Provider store={store}>{children}</Provider>;
};
function UpgradeBlockWithStore({ history, ...props } = {}) {
return mount(
<Router history={history}>
<MockProvider>
<UpgradeBlock {...props} />
</MockProvider>
</Router>
);
}
describe('71118716', () => {
test('should pass', () => {
const history = createMemoryHistory();
const wrapper = UpgradeBlockWithStore({ history });
const headerContainer = wrapper.find(HeaderContainer);
expect(headerContainer.exists()).toBe(true);
});
});
测试结果:
PASS stackoverflow/71118716/index.test.jsx (9.425 s)
71118716
✓ should pass (58 ms)
console.log
isHybrid: false
at UpgradeBlock (stackoverflow/71118716/index.jsx:7:11)
--------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
header.jsx | 100 | 100 | 100 | 100 |
index.jsx | 100 | 100 | 100 | 100 |
selectors.js | 100 | 100 | 100 | 100 |
--------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.023 s