Get empty array in redux-mock-store getActions - jestjs

making a request in my action. Pulling from api that need to return values from mock redux store. I have it start that request when redux mock store dispatch action, but i can't seem the values correctly when store.getActions().
I getting error store.getActions() is returning the state empty from the mock store .
For example:
simpleActions.js
export const fetchTodos = () => {
return async (dispatch) => {
const response = await axios.get('https://myweb.com/example.json');
dispatch({ type: types.FETCH_TODOS_REQUEST , payload: response.data });
}
}
simpleAction.test.js
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
describe('async actions', () => {
afterEach(() => {
fetchMock.restore()
})
it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', () => {
fetchMock.getOnce('/todos', {
body: { todos: ['do something'] },
headers: { 'content-type': 'application/json' }
})
const expectedActions = [
{ type: types.FETCH_TODOS_REQUEST },
{ type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something'] } }
]
const store = mockStore({ todos: [] })
const dispatchStored = store.dispatch(actions.fetchTodos());
return dispatchStored.then(() => {
**const values = store.getActions();**
This values is returning the state empty array from the mock store.
expect(store.getActions()).toEqual(expectedActions)
})
})
})
How to call or mock async/await function that need to return values instead of the state empty array from the mock store. Any helps would be appreciated.

Related

Trouble with return statement in Node Async Await

Trying to write a query for DynamoDB and learn promises etc. The console.log(resp.Items) returns the object that I am looking for so I think my query is formatted correctly. I get a status 200 back with an empty object.
I have read up for a few days and tried to implement various changes to the code by nothing is returning the object resp.Items. I am guessing the function is returning before the const is updated with the data but I am not sure why the console.log works.
const AWS = require('aws-sdk')
const dynamodb = new AWS.DynamoDB()
const getTechs = async () => {
try {
const resp = await dynamodb
.query({
ExpressionAttributeValues: {
':tech': { S: 'TECH#' },
},
KeyConditionExpression: 'PK = :tech',
TableName: process.env.TABLE_NAME,
ScanIndexForward: true,
})
.promise()
console.log(resp.Items)
if (!resp.Items) {
return {
error: 'No Techs in the DB',
}
}
return {
tech: resp.Items,
}
} catch (error) {
console.log('Error retrieving Tech List')
console.log(error)
return {
error: 'Could not retrieve Tech List',
}
}
}
handler func
const { makeHandler } = require('./utils')
const { getTechs } = require('../data')
// const { Tech } = require('../entities')
const inputSchema = {
type: 'object',
properties: {
pathParameters: {
type: 'object',
properties: {
tech: { type: 'string' },
},
required: ['tech'],
},
},
required: ['pathParameters'],
}
const handler = async (event) => {
const { techs, error } = await getTechs()
const statusCode = error ? 500 : 200
const body = error ? JSON.stringify({ error }) : JSON.stringify({ techs })
return {
statusCode,
body,
}
}
module.exports.handler = makeHandler({ handler })
executeTransactWrite func
const executeTransactWrite = async ({ tech, params }) => {
const transactionRequest = tech.transactWriteItems(params)
let cancellationReasons
transactionRequest.on('extractError', (response) => {
try {
cancellationReasons = JSON.parse(
response.httpResponse.body.toString()
).CancellationReasons
} catch (err) {
// suppress this just in case some types of errors aren't JSON parseable
console.error('Error extracting cancellation error', err)
}
})
return new Promise((resolve, reject) => {
transactionRequest.send((err, response) => {
if (err) {
err.cancellationReasons = cancellationReasons
return reject(err)
}
return resolve(response)
})
})
}
module.exports = {
executeTransactWrite,
makehandler func
const middy = require('middy')
const {
jsonBodyParser,
validator,
httpErrorHandler,
} = require('middy/middlewares')
const makeHandler = ({ handler, inputSchema }) =>
middy(handler)
.use(jsonBodyParser())
.use(validator({ inputSchema }))
.use(httpErrorHandler())
module.exports = { makeHandler }

Trying to load content with useEffect and context

I am trying to show information of a state into a component. I am using the context to load information from different origin.
const router = useRouter()
const [sidebarOpen, setSidebarOpen] = useState(false)
const [loadUser, setLoadUser] = useState({})
const { state, dispatch } = useContext(Context)
const { user } = state
useEffect(() => {
if (user == null) {
router.push("/auth/login")
}
setLoadUser(user)
}, [user])
That code is inside a dashboard component. The idea is to get the user information into the state to show it on the dashboard. The problem is that the useEffect is executed at the same time that the content is rendered, therefore it does not have time to load the information, and the variables are null for me.
Here is an image of how the loadState variable behaves once inside the render.
I am using nextjs by the way.
I am passing the context with a provider to the App. And wrapped it.
// initial state
const initialState = {
user: null
};
// Create context
const Context = createContext()
// root reducer
const reducer = (state, action) => {
const { type, payload } = action;
switch (type) {
case "LOGIN":
return { ...state, user: payload};
case "LOGOUT":
return { ...state, user: null };
default:
return state;
}
}
// context provider
const Provider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
const router = useRouter();
useEffect(() => {
dispatch({
type: "LOGIN",
payload: JSON.parse(window.localStorage.getItem("user"))
})
}, [])
axios.interceptors.response.use(
function (response) {
return response
},
function (error) {
let res = error.response;
console.log(error)
if (res.data.status === 401 && res.config && !res.config.__isRetryRequest) {
return new Promise((resolve, reject) => {
axios.get(`${process.env.NEXT_PUBLIC_API}/auth/logout`)
.then(res => {
dispatch({ type: "LOGOUT" })
window.localStorage.removeItem("user")
router.push('/auth/login')
})
.catch(error => {
reject(error)
})
})
}
return Promise.reject(error);
}
)
useEffect(() => {
const getCsrfToken = async () => {
const { data } = await axios.get(`${process.env.NEXT_PUBLIC_API}/csrf-token`)
axios.defaults.headers["X-CSRF-Token"] = data.csrfToken
}
getCsrfToken()
}, [])
return (
<Context.Provider value={{ state, dispatch }}>
{children}
</Context.Provider>
)
}
export { Context, Provider }
Add dependecy array. That shoud be quick fix.
useEffect(() => {
if (user == null) {
router.push("/auth/login")
}
setLoadUser(user)
}, [state]) // dependecy array looks at state changes
You can read more about dependecy array on the official react documentation: https://reactjs.org/docs/hooks-effect.html
proper fix:
whenever you are using api calls in your app, those are asyncrhonus. You should use some loading state.
for example
const Context = () => {
const [loading, setLoading] = useState(true)
const [user, setUser] = useState(true)
fetch('api/user').than(r=> setLoading(false);setUser(r.user))
// rest of the context code
}
and in component itself:
const state = useContext(Context)
useEffect(() => {
state.loading ? null : setLoadUser(user)
}, [state]) //

Execute function from object property

i have a little problem with my code.
My expectation is, when i get the object reqHeaders to the function getQueryData
i want that the property UUID will execute the function createToken().
currently, when i running the program, it happens only at the init( first time ).
const createToken = () => {
// some logics...
return `${token}`;
};
const reqHeaders = {
UUID: **createToken()**,
"Content-Type": "application/json;charset=UTF-8"
};
const getQueryData = query => {
return axiosInstance
.post("/someAddress", { selectQuery: query }, { headers: **reqHeaders** })
.then(response => {
// some logs...
return response.data;
})
.catch(error => {
//some logs....
return error;
});
}
};
module.exports = getQueryData;
thank you,
Raz.
The solution is to move the object creation inside the body of the function.
const createToken = () => {
// some logics...
return `${token}`;
};
const getQueryData = query => {
return axiosInstance
.post("/someAddress", { selectQuery: query }, { headers: {
UUID: **createToken()**,
"Content-Type": "application/json;charset=UTF-8"
} })
.then(response => {
// some logs...
return response.data;
})
.catch(error => {
//some logs....
return error;
});
}
};
module.exports = getQueryData;
Now each time you run the function new req headers will be created and hence the UUID. What you did previously created an object once and then use the same object for each function call.

I get undefined when reading my response but there is a response in React.js

I can't figure it out, the answer comes in the network table but when I want to console.log it, this will display undefined. Do you have any idea why? I attach the pictures and the code.
Here is a image with my codes and response
Here is the code - first one is where I send the response. As I said, it's going well on network tab, I get a 200 status.
export const getAccountStatus = async (req, res) => {
const user = await User.findById(req.user._id).exec();
const account = await stripe.accounts.retrieve(user.stripe_account_id);
// console.log("user account retrieve", account);
const updatedUser = await User.findByIdAndUpdate(
user._id,
{
stripe_seller: account
},
{ new: true }
)
.select("-password")
.exec();
console.log(updatedUser);
res.send(updatedUser);
};
Here is the page where i want to console.log it:
const StripeCallback = ({ history }) => {
const { auth } = useSelector(state => ({ ...state }));
const dispatch = useDispatch();
useEffect(() => {
if (auth && auth.token) accountStatus();
}, [auth]);
const accountStatus = async () => {
try {
const res = await getAccountStatus(auth.token);
console.log(res);
} catch (err) {
console.log(err);
}
};
return <div>test</div>;
};
Ang here is the Axios.post (which is working well as I know):
export const getAccountStatus = async token => {
await axios.post(
`${process.env.REACT_APP_API}/get-account-status`,
{},
{
headers: {
Authorization: `Bearer ${token}`
}
}
);
};
Thank you!
getAccountStatus doesn't have a return statement, so res in const res = await getAccountStatus(auth.token); will always be undefined.
export const getAccountStatus = async token => {
return axios.post( // <----- added return
`${process.env.REACT_APP_API}/get-account-status`,
{},
{
headers: {
Authorization: `Bearer ${token}`
}
}
);
};

Unit test for customPollingHook which uses apollo useLazyQuery

So I have written a custom polling hook which uses useContext and useLazyQuery hooks. I want to write a unit test for this, which should cover its returned values state and side effect.
So far I have managed to do this much but I'm not so sure how to proceed ahead. Any tips?
export const useUploadActivityPolling = (
teId: TeIdType
): UploadActivityPollingResult => {
const { dispatch, uploadActivityId }: StoreContextType = useAppContext();
const [fetchActivityStatus, { error: UploadActivityError, data: UploadActivityData, stopPolling }] = useLazyQuery(
GET_UPLOAD_ACTIVITY,
{
pollInterval: 3000,
fetchPolicy: 'network-only',
variables: { teId, activityId: uploadActivityId },
}
);
useEffect(() => {
if (UploadActivityData) {
setUploadActivityId(
UploadActivityData.getUploadActivityStatus.activity_id,
dispatch
);
updateActivityStateAction(UploadActivityData.getExcelUploadActivityStatus.status, dispatch);
}
}, [UploadActivityData]);
return { fetchActivityStatus, stopPolling, UploadActivityError };
};
import React from 'react';
import { mount } from 'enzyme';
const TestCustomHook = ({ callback }) => {
callback();
return null;
};
export const testCustomHook = callback => {
mount(<TestCustomHook callback={callback} />);
};
describe('useUploadActivityPolling', () => {
let pollingResult;
const teId = 'some id';
beforeEach(() => {
testCustomHook(() => {
pollingResult = useUploadActivityPolling(teId);
});
});
test('should have an fetchActivityStatus function', () => {
expect(pollingResult.fetchActivityStatus).toBeInstanceOf(Function);
});
});

Resources