这有点旧,但我想我会分享我的发现。
要做的第一件事也是最快的事情是在preact-router 中使用route 函数。
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 的 prop。因此,您可以使用 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.
});