我有一个组件在装载时分派(dispatch) fetch
请求,并显示结果。
我正尝试在请求完成后创建此组件的测试快照。很长一段时间以来,我一直在努力解决这个问题,这里是关于 SO 的相关问题,但我没有运气:
- Async component snapshot using Jest and Redux
- How do test async components with Jest?
- React+Jest - Testing async components and waiting for mount
- How to take a jest snapshot after axios fetched data in componentDidMount?
这是我的fetch
模拟:
// Mocking the global.fetch included in React Native
global.fetch = jest.fn()
// Helper to mock a success response (only once)
fetch.mockResponseSuccess = (body, status = 200) => {
fetch.mockImplementationOnce(() =>
Promise.resolve({
status,
json: () => Promise.resolve(JSON.parse(body))
})
)
}
// Helper to mock a failure response (only once)
fetch.mockResponseFailure = error => {
fetch.mockImplementationOnce(() => Promise.reject(error))
}
组件(简化):
export class Posts extends Component {
constructor(props) {
super(props)
this.state = {
items: [],
loading: false
}
this._getItems()
}
async _getItems() {
const resp = await fetch(
"/user/recent_posts",
{
method: "GET"
}
)
this.setState({
items: resp.json["data"],
})
}
render() {
// renders this.state.items
}
这是测试:
test("view renders correctly", async done => {
fetch.mockResponseSuccess(
JSON.stringify({
data: [
{ caption: "test", likes: 100 },
{ caption: "test2", likes: 200 }
]
})
)
// also tried with setTimeout and setImidiate
const wrapper = await shallow(<Posts />) // also tried with react-test-renderer
await wrapper.update() // didn't work with or without
// await waitForState(wrapper, state => state.loading === false) --> didn't work
// process.nextTick(() => {.... --> didn't work
// jest.runTimersToTime(1) --> didn't work
expect(wrapper).toMatchSnapshot()
done()
})
问题是快照中的this.state.items
总是空的。
最佳答案
为了将来引用,以下是为我解决的问题:
test("view renders correctly", done => {
// mock response here...
const wrapper = shallow(<Posts />)
setImmediate(() => {
wrapper.update()
try {
expect(wrapper).toMatchSnapshot()
} catch (e) {
console.log(e)
}
done()
})
})
关于javascript - React Native 异步 Jest 组件测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56627456/