gpt4 book ai didi

javascript - React Jest 测试无法读取未定义的属性 'pathname'

转载 作者:数据小太阳 更新时间:2023-10-29 05:24:47 27 4
gpt4 key购买 nike

不确定为什么我的简单 Main.test 文件中会出现此错误。

enter image description here

Main.js 的构造函数

export class Main extends Component {
constructor(props) {
super(props);

this.state = {
location: splitString(props.location.pathname, '/dashboard/')
}

if (R.isEmpty(props.view)) {
isViewServices(this.state.location)
? this.props.gotoServicesView()
: this.props.gotoUsersView()
}
}

主测试

import React from 'react'
import * as enzyme from 'enzyme'
import toJson from 'enzyme-to-json'
import { Main } from './Main'
import Sidebar from '../../components/Common/sidebar'

const main = enzyme.shallow(<Main />);

describe('<Main /> component', () => {

it('should render', () => {
const tree = toJson(main);
expect(tree).toMatchSnapshot();
});

it('contains the Sidebar', () => {
expect(main.find(Sidebar).length).toBe(1);
});
});

有没有办法模拟“路径名”?

最佳答案

看来您可能有一些错误,其中一个是您在测试中没有传递任何 Prop 。

另一个来自您在构造函数中访问 this.props

请参阅您的 if 语句,但我会在此处明确修复

if (R.isEmpty(props.view)) {
isViewServices(this.state.location)
? props.gotoServicesView()
: props.gotoUsersView()
}

在主测试中

const location = { pathname: '/dashboard/' };
const main = enzyme.shallow(<Main location={ location }/>);

关于javascript - React Jest 测试无法读取未定义的属性 'pathname',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45287894/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com