我一直有下面的错误,而我尝试运行下面的测试用例,它应该验证URL。如果需要,函数validateUrl应该为URL添加前缀“http://”。我这样做是因为我用的是API没有这个前缀:Jest TypeError:无法读取未定义的'商店'
import userDetail from '../src/container/user-detail'
describe('UrlValidation',() => {
it('should be a valid string',() => {
var result = new userDetail()
result.validateUrl("google.com")
exept (result).toBe("http://google.com")
})
})
userDetail看起来是这样的:
import React, { Component } from 'react';
import { connect } from "react-redux";
class UserDetail extends Component {
renderUser(userData){
return (
<tr key={userData.id}>
<td>
{userData.name}
</td>
<td>
<a target="_blank" href={this.validateUrl(userData.website)}>{userData.website}</a>
</td>
<td>
{userData.address.city}
</td>
<td>
<a>
<img alt="edit" src="./media/edit-icon.svg" className="edit-img"></img>
</a>
</td>
</tr>
);
}
validateUrl(providedUrl){
var url = providedUrl;
var r = new RegExp('/^(http|https):\/\/[^ "]+$/');
if (!r.test(url)) {
return "http://" + providedUrl
} else {
return providedUrl
}
}
render() {
const {users} = this.props
console.log(users.map(user => this.renderUser(user)));
return (
<table className="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Website</th>
<th>City</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
{users.map(user => this.renderUser(user))}
</tbody>
</table>
)}
}
function mapStateToProps({ users }){
return { users }; // { user } == { user: user }
}
export default connect(mapStateToProps)(UserDetail);
我不知道,什么是我的定义错误。
我首先想到函数validateUrl不可访问,但它应该是。
输出看起来是这样的:
[email protected] ~/dev/User-Manager/UserManagement $ npm test
[email protected] test /home/joshii/dev/User-Manager/UserManagement jest
FAIL tests/app.test.jsx UrlValidation ✕ should be a valid string (3ms)
● UrlValidation › should be a valid string
TypeError: Cannot read property 'store' of undefined 3 | describe('UrlValidation',() => { 4 | it('should be a valid string',() => { >5 | var result = new userDetail() 6 | result.validateUrl("google.com") 7 | exept (result).toBe("http://google.com") 8 | }) 9 | }) at new Connect (node_modules/react-redux/lib/components/connect.js:102:29) at Object.<anonymous> (__tests__/app.test.jsx:5:18)
Test Suites: 1 failed, 1 total Tests: 1 failed, 1 total Snapshots: 0 total Time: 0.744s, estimated 1s Ran all test suites. npm ERR! Test failed. See above for more details.
你有没有试过嘲笑传递REDX'商店'开玩笑? –
@JohnKennedy不,但我只是使用这个类,并给它一个字符串。它不使用任何来自redux商店的东西,还是我错了? –
你的根组件被封装在'provider'组件中,它把'store'作为一个道具。 –