Dim*_*fst 5 javascript unit-testing reactjs jestjs enzyme
我正在尝试测试我的功能ComponentDidMount
。但我收到此错误:Cannot destructure property params on null or undefined
.
我要测试的功能是这个:
componentDidMount() {
this.fetchUser();
}
Run Code Online (Sandbox Code Playgroud)
它取决于这个:
fetchUser = () => {
getUser(this.getUserUsername()).then(username => {
this.setState({
user: username.data
});
});
};
Run Code Online (Sandbox Code Playgroud)
作为回报取决于这个:
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;
};
Run Code Online (Sandbox Code Playgroud)
这是我的测试:
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);
});
});
Run Code Online (Sandbox Code Playgroud)
但我收到上述错误。不确定我需要做什么,虽然我找到了与此问题类似的答案,但这些答案并不能解决我的问题。
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);
};
Run Code Online (Sandbox Code Playgroud)
以上返回一个承诺。
尝试下面的语法
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();
});
});
Run Code Online (Sandbox Code Playgroud)
您也可以使用containsMatchingElement
归档时间: |
|
查看次数: |
8206 次 |
最近记录: |