[英]Jest & Enzyme | Test PropTypes Function in componentDidMount
I have this code in my component, that takes listUsers, as a required PropType func. 我的组件中有此代码,该代码将listUsers作为必需的PropType函数。 I want to test that in the
componentDidMount()
, it should be called only once. 我想测试在
componentDidMount()
,它应该只被调用一次。
Component Code: 组件代码:
static propTypes = {
securityMode: PropTypes.string.isRequired,
listUsers: PropTypes.func.isRequired
};
componentDidMount() {
const { listUsers } = this.props;
listUsers();
}
onCreateUserSucess= response => {
this.setState({ isCreateUserModalOpen: false });
const { listUsers, notify } = this.props;
listUsers();
this.closeCreateUserModal();
notify({
title: 'Created User',
message: `User ${response.username} was added to group: ${response.group}`,
status: STATUS.success,
dismissible: true,
dismissAfter: 3000
});
};
I get an error, saying that spyOn can only be appliead to functions. 我收到一个错误消息,说spyOn仅适用于函数。 Can someone help me to test the.
有人可以帮我测试一下。
componentDidMount
and onCreateUserSucess
. componentDidMount
和onCreateUserSucess
。 I even tried to mock the functions but I always get failings. 我什至尝试模拟功能,但总是失败。
Testing componentDidMount
is pretty simple. 测试
componentDidMount
非常简单。 Let's suppose that the component you created above is called UsersDisplayer
. 假设您在上面创建的组件称为
UsersDisplayer
。
class UsersDisplayer extends Component {
constructor(props) {
// ...
}
// The code above goes here.
}
In order to test whether the listUsers
function runs or not, you should do something similar to this: 为了测试
listUsers
函数是否运行,您应该执行以下操作:
// Import React, shallow and UsersDisplayer at the top.
describe('<UsersDisplayer />', () => {
let usersDisplayerWrapper;
let listUsers;
beforeEach(() => {
listUsers = jest.fn();
usersDisplayerWrapper = <UsersDisplayer listUsers={listUsers} />;
});
describe('componentDidMount', () => {
it('calls listUsers props function', () => {
// The `componentDidMount` lifecycle method is called during the rendering of the component within the `beforeEach` block, that runs before each test suites.
expect(listUsers).toHaveBeenCalled();
});
});
describe('onCreateUserSucess', () => {
it('calls listUsers props function', () => {
// Create a dummy `response` data that will be passed to the function.
const response = {
username: 'username',
group: 'group'
};
// Simply just call the function of the instance.
usersDisplayerWrapper.instance().onCreateUserSucess(response);
expect(listUsers).toHaveBeenCalled();
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.