MyComponent.js具有toLowerCase并包含在道具中。当我对MyComponent进行单元测试时,我得到toLowerCase并且include()不是函数。
MyComponent.js
this.props.currentUser.role.toLowerCase().includes('admin')
MyComponent.test.js
mount(<Provider store={store}>
<MyComponent />
</Provider>);
});
错误:
TypeError: this.props.currentUser.role.toLowerCase is not a function
TypeError: this.props.currentUser.role.includes is not a function
答案 0 :(得分:2)
您应该将currentUser对象作为道具传递给组件。
let user ={role:"test"}
mount(<Provider store={store}>
<MyComponent currentUser={user}/>
</Provider>);
});
答案 1 :(得分:0)
.toLowerCase()
和.include()
仅适用于字符串。确保要传递给道具的参数是字符串。在您的代码中,您没有传递任何道具,因此,基本上,您试图在未定义的类型上执行这些功能。尝试以下方法:
mount(<Provider store={store}>
<MyComponent currentUser={user}/> //Specify 'user' before
</Provider>);
答案 2 :(得分:0)
首先检查值是否存在以及角色是否为字符串,然后应用一些功能
this.props.currentUser && this.props.currentUser.role &&
this.props.currentUser.role.toString().toLowerCase().includes('admin') ? 'Yes included' or 'Not'
如果您使用 toLowerCase()函数,也请不要与 Admin 和 admin
进行比较