本文介绍了如何从酶挂载、反应还原状态下找到子组分连接亲本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下组件中,当isHybrid道具为真时,我向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道具值来检查<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并认为它是错误的。

推荐答案

我的测试策略:

  1. 创建模拟复制存储,而不是模拟选择器。
  2. 创建内存历史记录或使用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

这篇关于如何从酶挂载、反应还原状态下找到子组分连接亲本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 07:00