javascript - 笑话/酶 | 无法在 null 或 undefined 上解构属性
问题描述
我正在尝试测试我的功能ComponentDidMount
。但我得到这个错误:Cannot destructure property params on null or undefined
。
我要测试的功能是这个:
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);
});
});
但我收到上述错误。不知道我需要做什么,虽然我找到了与这个问题类似的答案,但答案并没有解决我的问题。
获取用户的代码:
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);
};
以上返回一个承诺。
解决方案
试试下面的语法
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
推荐阅读
- angular - TypeScript 中的接口和泛化
- php - 设置变量内容等于字符串并设置变量
- javascript - 为什么这个 Promise 中的 setState 比异步函数的相同代码需要更长的时间来更新?
- node.js - 如何接受小写、大写和混合大小写的查询字符串
- regex - 用于识别具有特殊字符和边界的字母数字模式的正则表达式
- python - 剪刀石头布分数不断重置
- python - 如何通过请求库异步获取数据而无需等待?
- ios - iOS MTKView (Metal Kit view) draws image without proper scale
- python - 如何使用 python 将嵌套的 JSON 数据转换为 CSV?
- python - 具有可变输入的自动编码器 Keras