我的组件中有这段代码,它采用 listUsers 作为必需的 PropType 函数。我想测试一下,在 componentDidMount()
中,它应该只被调用一次。
组件代码:
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
});
};
我收到一条错误,指出 spy On 只能应用于函数。有人可以帮我测试一下吗。 componentDidMount
和 onCreateUserSucess
。我什至尝试模拟这些功能,但总是失败。
最佳答案
测试componentDidMount
非常简单。假设您上面创建的组件名为 UsersDisplayer
。
class UsersDisplayer extends Component {
constructor(props) {
// ...
}
// The code above goes here.
}
为了测试 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();
});
});
});
关于javascript - Jest 与 enzyme |在 componentDidMount 中测试 PropTypes 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54907756/