reactjs 有没有可能用jest来测试你的react应用入口点?

jvidinwx  于 2022-12-12  发布在  React
关注(0)|答案(1)|浏览(142)

我有一个react应用程序,它有以下入口点:

// Import dependencies
import React from 'react';
import { render } from 'react-dom';
import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import configureStore from './store/configureStore';
import Root from './containers/Root';

const store = configureStore({});
const history = syncHistoryWithStore(browserHistory, store);

render(
  <Root store={store} history={history} />,
  document.getElementById('react')
);

一个非常常见的配置。我想知道你如何测试这样的东西,因为它不导出任何东西,而jest依赖于导入你想测试的东西。

uklbhaso

uklbhaso1#

首先,您可能不需要对此进行测试,但您绝对可以。
如果你真的想这么做,你需要重新构造你的代码,这样就有一个函数要测试:

// Import dependencies
import React from 'react';
import { render } from 'react-dom';
import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import configureStore from './store/configureStore';
import Root from './containers/Root';

export const app = () => {
   const store = configureStore({});
   const history = syncHistoryWithStore(browserHistory, store);

   render(
     <Root store={store} history={history} />,
     document.getElementById('react')
   );
};

然后,您可以使用react testing库之类的工具来确保将Root组件挂载到正确的元素中:

import { render, screen } from '@testing-library/react';
import { app } from './app';

test('app should render the Root component into the expected element', () => {
   // render the document with the element we plan on using for our react app
   render(<div id="react" />);

   // invoke the function that will render our component into that element
   app();

   // assert that the component exists in the document
   // you can mock `Root` to be some element you expect to see in the test
   // for the sake of this example, since I know nothing about `Root`
   // let's assume it has some identifying text
   expect(screen.getByText('rooty tooty toot toot')).toBeInTheDocument(); 
});

这样我们就可以在入口点用文本显示所做的工作,但现在它是一个需要调用的函数!要使应用正常工作,入口点需要导入app函数并调用它:

import { app } from './app';

app();

相关问题