首页 文章

测试路由器v4与开胃酶反应

提问于
浏览
2

我正在尝试用反应路由器v4和jest酶做一个简单的测试 .

describe('<App />', () => {

  it('renders a static text', () => {

    const wrapper = shallow(
    <MemoryRouter initialEntries={['/']} initialIndex={0}>
      <App/>
    </MemoryRouter>

    console.log(wrapper.html());
  );

  });
});

当我尝试console.log(wrapper.html())时,我得到:

Invariant Violation: [React Intl] Could not find required `intl` object. <IntlProvider> needs to exist in the component ancestry.

我正在使用反应锅炉板项目 . 我想做的就是测试当我给它一个'/'的路径时,主页会呈现一些文本 .

任何帮助赞赏!谢谢!

EDIT

This is the test:

it('test', () => {
    const wrapper = shallow(
      <MemoryRouter initialEntries={['/']} initialIndex={0}>
        <Route path="/" render={() => <App/>}/>
      </MemoryRouter>,
    );

    console.log(wrapper.find(App).html());
  });

这是App类:

export default function App() {
  return (
    <AppWrapper>
      <Helmet
        titleTemplate="%s - React.js Boilerplate"
        defaultTitle="React.js Boilerplate"
      >
        <meta name="description" content="A React.js Boilerplate application"/>
      </Helmet>
      <Header/>
      <Switch>
        <Route exact path="/" component={HomePage}/>
        <Route path="/features" component={FeaturePage}/>
        <Route
          path="/catalog"
          render={() => <div>hi</div>}
        />
        <Route path="" component={NotFoundPage}/>
      </Switch>
      <Footer/>
    </AppWrapper>
  );
}

这是运行测试时的错误消息:

**Error: Method “html” is only meant to be run on a single node. 0 found instead.**

我期待这个页面匹配,我将能够console.log输出它:

<Route exact path="/" component={HomePage}/>

2 回答

  • 1

    你为什么要调用 shallow 中的console.log?我以前从未见过这个...尝试将 <App /> 组件包装在 <Route /> 中,并在其中搜索一些标签 . 例如 . 假设你有这个简单的组件:

    <App>
      <h1>Hi there!</h1>
    </App>
    

    测试看起来像这样:

    describe('<App />', () => {
    
      it('renders a static text', () => {
    
        const wrapper = shallow(
          <MemoryRouter initialEntries={['/']} initialIndex={0}>
            <Route path="/" render={() => <App />} />
          </MemoryRouter>
        );
        console.log(wrapper.find(App).html());
      });
    });
    

    UPDATE 碰巧,react-boilerplate增加了太多的包装和依赖 . 因此,对于成功的测试,我们需要以不同的方式克服它们......

    这就是我完成它的方式(我的 react-boilerplate/app/tests/simple.test.js 的全部内容):

    import React from 'react';
    import { mount } from 'enzyme';
    import { MemoryRouter, Route, browserHistory } from 'react-router-dom';
    import { IntlProvider } from 'react-intl';
    import { Provider } from 'react-redux';
    
    import configureStore from '../configureStore';
    import App from '../containers/App';
    import { HomePage } from '../containers/HomePage';
    
    describe('test of initial load', () => {
      it('test', () => {
        const store = configureStore({}, browserHistory);
        const wrapper = mount(
          <MemoryRouter initialEntries={['/']} initialIndex={0}>
            <IntlProvider locale="en"> // to add Intl support
              <Provider store={store} > // to provide store for numeric connected components
                <Route path="/" render={() => <App />} />
              </Provider>
            </IntlProvider>
          </MemoryRouter>
        );
        process.nextTick(() => { // to wait for loadible component will be imported
          console.log(wrapper.find(HomePage).html());
        });
      });
    });
    

    我认为这是相当整合而不是单元测试...输出 console.log

    console.log app/tests/simple.test.js:24
      <article><!-- react-empty: 38 --><div><section class="sc-bxivhb jwizic"><h2 class="H2__H2-dhGylN kpbCLA"><span>Start your next react project in seconds</span></h2><p><span>A highly scalable, offline-first foundation with the best DX and a focus on performance and best practices</span></p></section><section class="Section__Section-jEbZoY eivjmS"><h2 class="H2__H2-dhGylN kpbCLA"><span>Try me!</span></h2><form class="Form__Form-PASBS cEpjmP"><label for="username"><span>Show Github repositories by</span><span class="AtPrefix__AtPrefix-ivHByA dZcxpA"><span>@</span></span><input type="text" class="Input__Input-ixjKAz jCPlXI" id="username" placeholder="mxstbr" value=""></label></form><!-- react-empty: 54 --></section></div></article>
    
  • 0

    超级简单的方法,无需所有 <MemoryRouter><Route> 标签

    在您的App组件中,将 export 添加到您的 class .

    export class App extends Component {
      render() {
        return (
          <div>Hi, there</div>
        );
      }
    }
    

    然后在 spec.js 文件中,只需导入组件进行测试,如下所示:

    import React from 'react'; 
    import {shallow} from 'enzyme'; 
    import { App } from './App';
    
    describe ('App component', () => {
    
      it('renders App', () => {
         const wrapper = shallow(<App optInValue={true} authenticated={true}/>);
    
         expect(wrapper.length).toEqual(1);   
      }); 
    });
    

相关问题