我正在尝试测试我的 ComponentDidMount
函数。但我收到此错误:无法在 null 或未定义时解构属性参数
。
我要测试的功能是这个:
componentDidMount() {
this.fetchUser();
}
这取决于这个:
fetchUser = () => {
getUser(this.getUserUsername()).then(username => {
this.setState({
user: username.data
});
});
};
这反过来取决于这个:
getUserUsername = () => {
const { match } = this.props;
const { params } = match;
console.log(params, 'params'); // return an object { username: "john" }
console.log(match, 'match');
**// return an object
// { isExact: true
// params:
// username: "john" .
// __proto__: Object
// path: "/management/users/:username"
// url: "/management/users/john" }**
return params.username;
};
这是我的测试:
describe('componentDidMount', () => {
it('should call fetchUsers function', () => {
const match = { params: 'testName' };
const params = match;
const fetchUserFn = jest.fn(params);
const wrapper = shallow(<UserDetailsScreen fetchUsers={fetchUserFn} />, {
disableLifecycleMethods: true
});
wrapper.instance().componentDidMount();
expect(fetchUserFn).toHaveBeenCalledTimes(1);
});
});
但是我收到了上述错误。不确定我需要做什么,虽然我找到了与此问题类似的答案,但这些答案并不能解决我的问题。
getUser 的代码:
export const getUser = username => {
const options = {
method: httpMethod.GET,
url: endpoint.GET_USER(username)
// The GET_USER is an endpoint for
// that specific username
};
return instance(options);
};
上面返回一个 promise 。
最佳答案
尝试以下语法
describe('componentDidMount', () => {
it('should call fetchUsers function', () => {
const match={params: {username: 'akshay'}, isExact: true, path: "", url: ""}
const fetchUserFn = jest.fn(match);
const wrapper = shallow(<UserDetailsScreen match={match} fetchUsers={fetchUserFn} />, {
disableLifecycleMethods: true
});
expect(wrapper.containsMatchingElement(<h2>Details for 1</h2>)).toBeTruthy();
});
});
您也可以使用containsMatchingElement
关于javascript - Jest/ enzyme |无法解构 null 或未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55118126/