I have this code in my component, that takes listUsers, as a required PropType func. I want to test that in the componentDidMount()
, it should be called only once.
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. Can someone help me to test the. componentDidMount
and onCreateUserSucess
. I even tried to mock the functions but I always get failings.
Testing componentDidMount
is pretty simple. Let's suppose that the component you created above is called 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:
// 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();
});
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.