我刚刚进入项目的单元测试,适配器已正确设置,并且编写了一些测试。我的一些测试会引发错误,即那些包含来自redux状态的变量的错误。以下只是其中之一:
export class BasePage extends React.Component {
componentDidMount() {
const baseId = this.props.match.params.baseId;
const access_token = this.props.auth;
if (this.props.match.params.baseId) {
this.props.dispatch(fetchSingleBase(baseId, access_token));
}
}
}
下面的componentDidMount
中也发生了以下命名的错误,但是我可以通过if
语句来缓解这种情况。
BasePage
是通过Router在app.js中呈现的:
return (
<div>
<Navbar />
<main>
...
<Route exact path="/single-base/:baseId" component={BasePage} />
</main>
</div>
);
在基本页面上,我返回:
return (
<div className="basepage">
{title}
<UserList baseId={this.props.match.params.baseId} />
<MessageList baseId={this.props.match.params.baseId} />
</div>
);
如果此处的语句不起作用。 运行npm测试时,出现以下错误消息:
TypeError: Cannot read property 'params' of undefined
最后,测试的基本知识:
import React from "react";
import ConnectedBasePage, { BasePage } from "./basepage";
import { shallow, mount, render } from "enzyme";
describe("<BasePage/>", () => {
it("Renders without crashing", () => {
shallow(<BasePage/>);
});
});
如何解决此错误?
答案 0 :(得分:0)
您需要传递模拟匹配对象:
const match = {
params : {
baseId : 1 //any id you want to set
}
}
describe("<BasePage/>", () => {
it("Renders without crashing", () => {
shallow(<BasePage match={match}/>);
});
});