【发布时间】:2019-07-10 17:45:40
【问题描述】:
我有一个看起来像这样的 if 条件:
if (history.state !== null && history.state.query)
问题在于,虽然这在 Jest 中不起作用,因为 history 在我的测试中是一个空对象。
在我的测试中需要做什么才能使用history 对象?我在 Node.js 服务器上使用 React 运行它。不确定这是否重要,但我也在使用 React Router。
测试用例:
beforeEach(() => {
window.ga = jest.fn();
window.analytics = jest.fn();
window.analytics.track = jest.fn();
});
it('should set up props from history state', () => {
let location = {
pathname: '/explore',
query: {
query: 'yahoo',
},
};
global.history = { state: { query: 'google'} };
const wrapper = mount(
<LandingPage location={location} />
);
console.log("global.history.state: " + global.history.state); // prints null
});
部分组件(不能放整个组件):
if (props.location && props.location.pathname === '/explore') {
explorePath = true;
skipIntro = true;
explore = true;
/* checks if history.state is not equal to null
* if check passes, search query and results will appear
*/
if (history.state !== null && history.state.query) {
currentValue = history.state.query;
employeeMin = history.state.eMin;
employeeMax = history.state.eMax;
revenueMin = history.state.rMin;
revenueMax = history.state.rMax;
}
} else {
explore = skipIntro;
}
【问题讨论】:
-
你使用什么版本的 react-router?你是否从组件中的 props 中检索历史记录?
-
那么您可以通过将
state.query添加到空对象来模拟history吗? -
@hinok 我使用来自
window的全局history。我相信版本是3.0.2。 -
@VincentTaing 我试过模拟,但是当我模拟时没有用
global.window = {history:{state:{query:"..."}}};我应该以不同的方式模拟它吗? -
@RaDeuX 你能告诉我们你要测试的组件和测试用例吗?