【发布时间】:2019-03-13 23:43:50
【问题描述】:
我有一个执行fetchUser() 的componentDidMount。我正在尝试测试componentDidMount。
组件代码:
static propTypes = {
match: PropTypes.shape({
isExact: PropTypes.bool,
params: PropTypes.object,
path: PropTypes.string,
url: PropTypes.string
}),
label: PropTypes.string,
actualValue: PropTypes.string,
callBack: PropTypes.func
};
state = {
user: {}
};
componentDidMount() {
this.fetchUser();
}
getUserUsername = () => {
const { match } = this.props;
const { params } = match;
return params.username;
};
fetchUser = () => {
getUser(this.getUserUsername()).then(username => {
this.setState({
user: username.data
});
});
};
测试:
it('should call fetchUsers function only once', () => {
const match = { params: { username: 'testUser' }, isExact: true, path: '', url: '' };
const fetchUserFn = jest.fn(match);
const wrapper = shallow(<UserDetailsScreen match={match} fetchUsers={fetchUserFn} />);
wrapper.instance().componentDidMount(match);
expect(fetchUserFn).toHaveBeenCalledTimes(1); // I get expected 1 and got 0
});
我的意思是为什么这个componentDidMount() 的测试与我的其他测试不同?在过去的几周里,我已经测试了其中很多,从来没有这个问题。也许是因为getUser() 是一个承诺,我需要模拟它。以前有没有人偶然发现过这样的事情?
getUser()的代码
export const getUser = username => {
const options = {
method: httpMethod.GET,
url: endpoint.GET_USER(username)
};
return instance(options);
};
【问题讨论】:
-
我将发布整个组件,但是如果我使用 wrapper.debug() 打印,我可以看到整个组件正在渲染,并且在我检查填充的特定数据的其他测试中,那些测试通过。
标签: javascript reactjs unit-testing jestjs enzyme