Component:componentDidMount setstate không phản ánh trong thử nghiệm Enzyme
import React from 'react'
import request from 'superagent'
export default React.createClass({
getInitialState() {
return {cats: []}
},
componentDidMount() {
request('/api', (err, res) => {
if (err) return;
this.setState({
cats: res.body.results
})
})
},
render() {
let cats = this.state.cats
let catsList = (
<ul>
{cats.map((c) => <li key={c.id}>cat</li>)}
</ul>
)
return (
<div>
hello world
{cats.length ? catsList : null}
</div>
)
}
})
Test:
jest.unmock('../app.js')
jest.unmock('superagent')
import React from 'react'
import {mount} from 'enzyme'
import nock from 'nock'
import App from '../app.js'
describe('App',() => {
let ajaxFn
beforeEach(() => {
ajaxFn = nock('http://localhost')
.get('/api')
.reply(200, {
results: [{id: 1}, {id: 2}, {id: 3}]
})
})
it('says hello world',() => {
let wrapper = mount(<App/>)
expect(wrapper.text()).toContain('hello worl')
})
it('makes ajax request',() => {
let wrapper = mount(<App/>)
expect(ajaxFn.isDone()).toBe(true)
})
it('renders correct number of cats',() => {
let wrapper = mount(<App />)
expect(wrapper.state('cats').length).toBe(3)
})
})
2 bài kiểm tra đầu tiên vượt qua nhưng một trong những thức không, tức là wrapper.state ('mèo') .length == 0
Tôi hiểu rằng setState không đảm bảo cập nhật trạng thái ngay lập tức, tuy nhiên nếu tôi đăng nhập 'mèo' trong thành phần, tôi có thể thấy cập nhật.
Cố gắng đó, nhưng nó đã không làm việc. –
Điều này làm việc cho tôi, tôi tự hỏi tại sao nó không cập nhật như là kết quả của setState, hiện các wrapper đi qua một bản sao của cây render hoặc một cái gì đó? – riscarrott
Leland, bạn không cần phải đảm bảo đầu tiên cập nhật trạng thái đó đã xảy ra trước khi thực hiện wrapper.update()? – bodrin