测试预先路由器的路由功能

时间:2020-01-29 05:35:09

标签: javascript reactjs react-router preact-router

如何在下面的代码中测试路由器?使用React时,您可以使用MemoryRouter传递initialEntries来模拟路由更改,但是我找不到替代的preact-router。我查看了Preact文档和preact-router文档,但找不到清晰的解决方案。

import 'preact/debug';
import { h, render } from 'preact';
import HomePage from './pages/homepage';
import Router from 'preact-router';
import AsyncRoute from 'preact-async-route';
import './styles/index.scss';

const App = () => (
  <Router>
    <HomePage path="/" />
    <AsyncRoute
      path="/admin"
      getComponent={ () => import('./pages/admin').then(module => module.default) }
    />
  </Router>
);

export default App;

1 个答案:

答案 0 :(得分:0)

这有点旧,但我想我会分享我的发现。

第一个也是最快的方法是使用 route 中的 preact-router 函数。

import { render, route } from 'preact-router';

import App from './App';

describe('<App/>', () => {
    it('renders admin', async () => {
        const { container, findByText } = render(<App/>);
        // Go to admin page
        route('/admin');
        // Wait for page to load since it's loaded async
        await findByText(/Admin Page/);
        // perform expectations.
    });
});

虽然这可行,但我不喜欢它依赖于浏览器的真实历史。幸运的是,<Router> 组件接受 history 类型的 CustomHistory 道具。因此,您可以使用 History API 的内存中实现来实现这一点。我想我已经看到建议使用 history 包的文档 - 但是我不得不进行调整

import { createMemoryHistory } from 'history';

class MemoryCustomHistory {
    constructor(initialEntries = undefined) {
      this.wrapped = createMemoryHistory({initialEntries});
    }
    get location() {
        return this.wrapped.location;
    }
    // Listen APIs not quite compatible out of the box.
    listen(callback) {
        return this.wrapped.listen((locState) => callback(locState.location));
    }
    push(path) {
        this.wrapped.push(path);
    }
    replace(path) {
        this.wrapped.replace(path);
    }
}

接下来,更新您的应用以接受要传递给 history

<Router> 属性
const App = ({history = undefined} = {}) => (
  <Router history={history}>
    <HomePage path="/" />
    <AsyncRoute
      path="/admin"
      getComponent={ () => import('./pages/admin').then(module => module.default) }
    />
  </Router>
);

最后,只需更新测试即可将您的自定义历史记录连接到应用。

  it('renders admin', async () => {
    const history = new MemoryCustomHistory(['/admin]);
    const { container, findByText } = render(<App history={history}/>);
    // Wait for page to load since it's loaded async
    await findByText(/Admin Page/);
    // perform expectations.
  });