javascript - 测试 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;
解决方案
这有点旧,但我想我会分享我发现的东西。
要做的第一件事也是最快的事情是只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
类型为 prop 的 prop 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.
});
推荐阅读
- ios - SwiftUI 文本视图不使用本地化的字符串字典文件
- javascript - 404 错误未在 GitHub 页面上加载我的 .js 文件
- ansible - Ansible:从 RPM Fusion 导入 GPG 密钥不起作用
- c# - 在 EF Core 迁移管理 CLI 中使用 -Context/--context 标志指定通用 DbContext
- node.js - axios 中的 Catch 块在部署到 heroku 时不起作用,但是当我在本地运行代码时它工作得很好
- google-apps-script - 我想从谷歌文档中的谷歌电子表格数据库中获取带有图像的pdf作为模板
- ruby - 仅当在 ruby 中使用 i18n api 时,如何将我的 www.example.com/en 设置为 www.example.com?
- c++ - RVO 是预期的,但没有发生
- python - TypeError show_poll() 得到了一个意外的关键字参数 's'
- json - 来自本地 json 的数据不显示在 FlatList 中