酶无法从ComponentDidMount读取this.props.match.params

问题描述 投票:0回答:1

我刚刚进入我的项目的单元测试,适配器设置正确,我写了一些测试。我的一些测试会抛出错误,即我在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/>);
    });
});

如何解决这个错误?

reactjs unit-testing redux jestjs enzyme
1个回答
0
投票

你需要传递模拟匹配对象:

const match = {
                params : { 
                            baseId : 1 //any id you want to set
                         }
               }

describe("<BasePage/>", () => {
it("Renders without crashing", () => {
    shallow(<BasePage match={match}/>);
 });
});
© www.soinside.com 2019 - 2024. All rights reserved.