Reactjs 使用API调用和Redux模拟函数组件
我有一个App.js文件Reactjs 使用API调用和Redux模拟函数组件,reactjs,unit-testing,web-applications,jestjs,enzyme,Reactjs,Unit Testing,Web Applications,Jestjs,Enzyme,我有一个App.js文件 const App = props => { const { userProfile, fetchUserProfile } = props useEffect(() => { fetchUserProfile() }, []) return userProfile === null ? <></> : <Dashboard /> } const mapStateToProps
const App = props => {
const {
userProfile,
fetchUserProfile
} = props
useEffect(() => {
fetchUserProfile()
}, [])
return userProfile === null ? <></> : <Dashboard />
}
const mapStateToProps = state => ({
userProfile: state.userProfile
})
export default connect(mapStateToProps, actions)(App)
商店:
export default createStore(
rootReducer,
composeEnhancers(applyMiddleware(thunk)),
)
我安装了jest和Ezyme来对这个类和其他类进行单元测试:
下面是我的代码:Import语句
import "jest-dom/extend-expect";
import React from 'react'
import { shallow } from "enzyme";
import ReactDOM from 'react-dom'
import { useSelector, useDispatch } from 'react-redux';
import App from './App'
import renderer from 'react-test-renderer';
第一代码
beforeAll(() => {
global.fetch = jest.fn();
//window.fetch = jest.fn(); if running browser environment
});
let wrapper;
beforeEach(() => {
const mockDispatch = jest.fn();
jest.mock('react-redux', () => ({
useSelector: jest.fn(),
useDispatch: () => mockDispatch
}));
jest.mock('./redux/actions', () => ({
fetchUserProfile: jest.fn(() => useDispatch({
type: SET_PROFILE,
payload: {
"user_id": "myuserid",
"username": "username",
"email": "emailID",
"date_joined": "2020-07-23T18:41:43+00:00",
"is_staff_user": false,
"is_super_user": false
},
}))
}))
wrapper = shallow(<App />, { disableLifecycleMethods: true });
});
afterEach(() => {
wrapper.unmount();
});
beforeAll(()=>{
global.fetch=jest.fn();
//window.fetch=jest.fn();如果运行浏览器环境
});
让包装纸;
在每个之前(()=>{
const mockDispatch=jest.fn();
mock('react-redux',()=>({
useSelector:jest.fn(),
useDispatch:()=>mockDispatch
}));
嘲笑('./redux/actions',()=>({
fetchUserProfile:jest.fn(()=>useDispatch({
类型:SET_PROFILE,
有效载荷:{
“用户id”:“我的用户id”,
“用户名”:“用户名”,
“电子邮件”:“电子邮件ID”,
“加入日期”:“2020-07-23T18:41:43+00:00”,
“is_staff_user”:false,
“是超级用户”:false
},
}))
}))
wrapper=shall(,{disableLifecycleMethods:true});
});
之后(()=>{
wrapper.unmount();
});
抛出错误
Details:
SyntaxError: /Users/jatingarg/PATH/src/App.test.js: Unexpected token (40:20)
38 | }))
39 |
> 40 | wrapper = shallow(<App />, { disableLifecycleMethods: true });
| ^
41 | });
42 |
43 | afterEach(() => {
详细信息:
语法错误:/Users/jatingarg/PATH/src/App.test.js:意外令牌(40:20)
38 | }))
39 |
>40 | wrapper=浅(,{disableLifecycleMethods:true});
| ^
41 | });
42 |
43 |每次之后(()=>{
此API使用缓存在浏览器中的令牌
有人能建议什么是正确的测试方法吗
我是ReactJS上的noob您是否尝试过
wrapper=shall((),{disableLifecycleMethods:true});
?在进行更改后,它也会抛出相同的错误
Details:
SyntaxError: /Users/jatingarg/PATH/src/App.test.js: Unexpected token (40:20)
38 | }))
39 |
> 40 | wrapper = shallow(<App />, { disableLifecycleMethods: true });
| ^
41 | });
42 |
43 | afterEach(() => {