是否可以用jest测试react应用程序的入口点?

Is it possible to test your react app entry point with jest?

本文关键字:应用程序 入口 react 测试 jest 是否      更新时间:2023-09-26

我有一个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依赖于导入您想要测试的内容。

首先,您可能不需要测试这个,但您绝对可以。

如果你真的想要这样做,你需要重构你的代码,以便有一个函数来测试:

// 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测试库之类的东西来确保你将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();