![](/img/trans.png)
[英]Best practice to test propTypes with jest + enzyme + react-redux?
[英]Jest & Enzyme | Test PropTypes Function in componentDidMount
我的組件中有此代碼,該代碼將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
});
};
我收到一個錯誤消息,說spyOn僅適用於函數。 有人可以幫我測試一下。 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();
});
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.