我刚刚进入我的项目的单元测试,适配器设置正确,我写了一些测试。我的一些测试会抛出错误,即我在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
通过app.js中的Router呈现:
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/>);
});
});
如何解决这个错误?
你需要传递模拟匹配对象:
const match = {
params : {
baseId : 1 //any id you want to set
}
}
describe("<BasePage/>", () => {
it("Renders without crashing", () => {
shallow(<BasePage match={match}/>);
});
});