我一直有下面的錯誤,而我嘗試運行下面的測試用例,它應該驗證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'作爲一個道具。 –