我已经为自定义钩子创建了一个测试。全部测试通过,但我收到错误消息,不确定如何找到根本原因。我正在尝试阅读此link,但找不到任何有用的信息。 挂钩只是有一个axios请求。没有任何地方可以直接分配location.href,这是我看到的另一件事,通常是导致此错误的原因
import axios from 'axios'
jest.mock('axios')
describe('hooks', ()=>{
it('test custom hook', async()=>{
const { result, waitForNextUpdate } = await renderHook(()=> customHook())
axios.get.mockResolvedValue(dataJSON)
expect(axios.get).toHaveBeenCalledTimes(1) // received 0
await waitForNextUpdate()
expect(axios.get).toHaveBeenCalledTimes(1) //received 2
})
})
错误:
console.error node_modules/jest-environment-jsdom-thirteen/node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Error: connect ECONNREFUSED 127.0.0.1:80
at Object.dispatchError (C:\project\node_modules\jest-environment-jsdom-thirteen\node_modules\jsdom\lib\jsdom\living\xhr-utils.js:60:19)
at Request.client.on.err (C:\project\node_modules\jest-environment-jsdom-thirteen\node_modules\jsdom\lib\jsdom\living\xmlhttprequest.js:674:20)
at Request.emit (events.js:203:15)
at Request.onRequestError (C:\project\node_modules\request\request.js:877:8)
at ClientRequest.emit (events.js:198:13)
at Socket.socketErrorListener (_http_client.js:401:9)
at Socket.emit (events.js:198:13)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:63:19) undefined
jest-config:
"jest": {
"moduleNameMapper": {
"\\.(css|less|sass)$": "<rootDir>/_mocks_/styleMock.js"
},
"collectCoverageFrom": [
"**/*.{js,jsx,ts,tsx}",
"!<rootDir>/node_modules/",
"!src/index.js",
"!src/i18n.js",
"!<rootDir>/_mocks_/*",
"!src/setupProxy.js",
]
}
自定义挂钩:
import { useState, useEffect, useCallback } from 'react'
import axios from 'axios'
const userDetailState = {
userInfo: '',
loading: true,
errorText: '',
}
export const customHook = () => {
const [userDetails, setUserDetails] = useState(userDetailState)
const transformData = useCallback(
(result) => {
setUserDetails({
...userDetails,
userInfo: result.data,
loading: false
})
},
[userDetails]
)
const getUserData = useCallback(async () => {
try {
const result = await axios.get('/userdetails')
transformData(result)
} catch (error) {
setUserDetails({
...userDetails,
loading: false
})
}
}, [transformData, userDetails])
useEffect(() => {
getUserData()
}, [])
return {
userDetails
}
}
userProvider:
import React, { useEffect } from 'react'
import { Loading } from 'components'
import UserContext from 'context/UserContext'
import { customHook } from 'hooks/User/customHook'
const UserProvider = () => {
const { userDetails } = customHook()
const renderContent = () => {
if (userDetails.loading) {
return (
<div className='loading'>
<Loading size='large' data-testid='userProfileLoadingId' className='loading-content' />
</div>
)
} else return dashbaordComponent
}
const contextValue = {
userDetail: userDetails.userInfo,
}
return (
<UserContext.Provider value={contextValue}>
{renderContent()}
</UserContext.Provider>
)
}