首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试preact-router的路由能力

测试preact-router的路由能力
EN

Stack Overflow用户
提问于 2020-01-29 13:35:10
回答 1查看 194关注 0票数 1

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

代码语言:javascript
复制
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;
EN

回答 1

Stack Overflow用户

发布于 2020-12-24 05:24:30

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

第一件也是最快的一件事就是在preact-router中使用route函数。

代码语言:javascript
复制
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>组件接受CustomHistory类型的history属性。因此,您可以使用History API的内存实现来实现这一点。我想我已经看过建议使用history包的文档了--但是我不得不做一个调整

代码语言:javascript
复制
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);
    }
}

接下来,更新应用程序以接受要传递给<Router>history属性

代码语言:javascript
复制
const App = ({history = undefined} = {}) => (
  <Router history={history}>
    <HomePage path="/" />
    <AsyncRoute
      path="/admin"
      getComponent={ () => import('./pages/admin').then(module => module.default) }
    />
  </Router>
);

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

代码语言:javascript
复制
  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.
  });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59961011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档