Manual mocks with Jest -- I'm not understanding something - reactjs

I'm learning jest, and trying to do a manual mock for an api, I'm missing something.
I'm mocking an api call to giphy. I'm seeing a lot of different syntaxes for the manual mocks, and unfortunately, they're not making much sense to me right now. I've been trying to code along with https://hackernoon.com/api-testing-with-jest-d1ab74005c0a and https://facebook.github.io/jest/docs/en/tutorial-async.html, but I'm stuck.
I have a component called GifListContainer that displays 3 gifs, there's search functionality, I just want a manual mock with fake data to learn.
I'm using create-react-app, I see a lot of people using isomorphic-fetch and other packages, but since jest is built in can't I do it without adding anything else?
I can't figure out how to manually write the mock, I feel I'm missing something simple. It's testing fine if I don't use the mock (using different testing syntax because I'm not testing the _ mock _ file). Thank you for your time.
The error I'm getting:
● should load gifs
TypeError: GifContainer.api is not a function
at Object.<anonymous>.it (src/Part_2/GifContainer.test.js:10:23)
✕ should load gifs (6ms)
GifListContainer.js
import {gifApi} from './api'
class GifListContainer extends Component {
state = {
gifs: []
};
componentDidMount() {
this.displayGifs('coding');
}
displayGifs = (query) => {
gifApi(query)
.then(res => res.json())
.then(json => {
let firstThreeGifs = json.data.slice(0, 3);
let urls = firstThreeGifs.map(
gif => gif.images.original.url.split("?")[0]
);
this.setState({
gifs: [...urls]
});
});
};
//after this there's a search function and the render and such.
api.js
const urlPartOne = "http://api.giphy.com/v1/gifs/search?q="
const urlPartTwo = "&api_key=UE0dCN2WofIwVF0RPbpHo0Lz0k9VhqdG"
const gifApi = (query) => {
return fetch(urlPartOne + query + urlPartTwo)
}
export {gifApi}
GifContainer.test.js
import React from 'react'
let mockFunction = jest.mock('./api.js');
import * as GifContainer from './GifContainer';
it('should load gifs', () => {
return GifContainer.displayGifs('sunshine')
.then(data => {
expect(data).toBeDefined()
expect(data.entity.data.type).toEqual('gif')
})
})
_ mocks _/api.js
I'm really just not getting how to write this.
const fs = require('fs')
const api = (query) => new Promise((resolve, reject) => {
fs.readFile(`./src/Part_2/__mockData__/query.json`, 'utf8', (err, data) => {
if (err) reject(err)
resolve({ entity: JSON.parse(data) })
})
})
export default api
and then mock data in a folder _ mockData _/sushine.json
/* http://api.giphy.com/v1/gifs/search?q=sunshine&api_key=UE0dCN2WofIwVF0RPbpHo0Lz0k9VhqdG */
{
"data": [
{
"type": "gif",
}
],
"meta": {
"status": 200,
"msg": "OK",
"response_id": "5b11716a33554c732e0ddf42"
}
}
Thank you!

I don't think so the problem is on the mock itself.
Actually, first of all you need to improve the way you are doing react unit testing.
Nowadays, there are tools like Enzyme(http://airbnb.io/enzyme/) which helps you a lot to test React components.
Have you check the Testing React Apps section for Jest? Specially the DOM Testing part? Take a look here: https://facebook.github.io/jest/docs/en/tutorial-react.html#dom-testing
Back to your problem, I think it's because you are exporting the fn as default in the mock file but haven't done that on the api file. Try to put both equals and let me know!

Related

Mocking hook firestore data in cypress

I have hook which downloads data from firestore and I am trying to mock this data in cypress tests. I am trying to do it with cy.intercept() but is not working as cypress still takes data from firestore instead of taking in it from todos.json(). Can it be fixed or maybe I should take different approach to actually try mock hook. If so - how can it be done?
describe("Todo actions", () => {
beforeEach(() => {
cy.visit("localhost:3000");
});
it("filtering by name", () => {
cy.intercept(
"GET",
"https://firestore.googleapis.com/google.firestore.v1.Firestore/Listen/channel?gsessionid=Jxzmhr-WFyT0LyY1M3YlRf__I7Mjuh0z3h-hTaCRr0E&VER=8&database=projects%2Ftodos-d2fcf%2Fdatabases%2F(default)&RID=rpc&SID=ZNjOxc2aZe3ayyf87HY8IA&CI=0&AID=0&TYPE=xmlhttp&zx=iq073faeg7z7&t=1",
{ fixture: "todos.json" }
);
});
});

Testing a component in Next.js with testing-library that relies on tRCP

I was experimenting with tRCP and diligently followed the setup for my Next.js project described in the official docs over here: https://trpc.io/docs/nextjs
However I noticed that a simple component that relies on tRPC such as this
export const Sample = () => {
const { data } = trpc.useQuery(['hello', { text: 'User' }]);
if (data === undefined) {
return <div>Loading...</div>;
}
return <div>{data.greeting}</div>;
};
cannot be properly tested since the following trivial test
describe('Sample', () => {
it('should render successfully', () => {
const { baseElement } = render(<Sample />);
expect(baseElement).toBeTruthy();
});
});
since there is no setup of provider such as the setup with the withTRCP HOC used for the application itself. As such the test fails claiming client (presumably the trcpClient, unlike the queryClient) is undefined.
I'd like to know how to setup the test correctly, in this case providing a correct client, as well as mocking the queries, since I don't have the respective server-side code running while invoking the tests.
Since you are getting undefined for the trpc client implementation, you can try spying on the query call.
import trpc from 'utils/trpc'; // This is the client implementation
describe('Sample', () => {
it('should render successfully', () => {
jest.spyOn(trpc, 'useQuery')
.mockReturnValue({ greeting: "Greeting" });
const { baseElement } = render(<Sample />);
expect(baseElement).toBeTruthy();
});
});
This is also possible with the mutations but you need to provide a mock implementation for the useMutation response for mutate property.

Cypress: Not able to stub with a basic example. What might i be missing?

For some reason, I am not able to stub this here. I have reduced my code to almost exactly this here. This should work according to the docs, but I'm wondering if I'm missing a finer detail of typescript / react hooks? That doesn't feel at all like the case but who knows. Thanks ahead of time if you're reading this and taking up your time. I appreciate what you do. Here's my example:
// connection.ts (the method to stub)
export const connectFn = async () => {
return 'i should not be here'
}
// ./reactHook.ts
import { connectFn } from './connection'
export const useMyHook = () => {
const handleConnect = async () => {
const result = await connectFn()
console.log(result)
// expected: 'i have been stubbed!'
// actual: 'i should not be here
}
return {
handleConnect
}
}
// ./App.ts
export const App = () => {
const { handleConnect } = useMyHook()
return <button onClick={handleConnect}>Connect</button>
}
// ./cypress/integration/connection.spec.ts
import * as myConnectModule from '../../connection'
describe('stub test', () => {
it('stubs the connectFn', () => {
cy.stub(myConnectModule, 'connectFn').resolves('i have been stubbed!')
cy.get('[data-testid=connect-btn]').click()
// assertions about the view here...
})
})
I thought I understood the cypress and Sinon docs pretty well. I have read that cypress needs an object to a stub from and not the named export directly - hence the * as an import. I have also tried every which way to export it as well. I used their example from the docs directly to no avail. I then thought it may be a typescript issue but it doesn't seem to be the case. I have reduced my actual code to pretty much this example here. I have even removed everything but the logs for testing and I'm still not getting it.
To stub successfully you need to stub (replace) the same instance.
In reactHook.ts
import { connectFn } from './connection'
if (window.Cypress) {
window.connectFn = connectFn
}
In the test
cy.window().then(win => {
cy.stub(win, 'connectFn').resolves('i have been stubbed!')
cy.get('[data-testid=connect-btn]').click()
...
}}
BTW useMyHook implies a React hook, if so you may need a cy.wait(0) to release the main JS thread and allow the hook to run.

Using Jest Mock API Calls to SetState

I have an API call which runs whenever a certain component mounts. If this API call is successful the response data is used to update the state of one of my React Hooks.
The issue I am having is either related to asynchronicity or a poorly formatted mock API call, but no matter what I try I cannot get this test to work.
Here is a simplified version of the API:
const getOrg =() => {
axios.get(URL, config)
.then(response => response.data)
.then(data => {
setOrgTitle(data.name)
}
}
Basically the API is triggered and my setOrgTitle hook is updated from the response.
const [orgTitle, setOrgTitle] = useState("");
Now in my return statement I am displaying the value of orgTitle:
<h1 className={styles.titleText} id="document-folders-h1">
{orgTitle} Folders
</h1>
Alright, so the component is pretty simple. When I am trying to test things my two ideas were to either set the initial orgTitle hook state in my test or to mock the API. After some research I decided mocking the API was the way to go.
So I have a mockAxios component:
const mockAxios = {
get: jest.fn(() => Promise.resolve({ data: {} }))
};
module.exports = mockAxios;
And my test file:
import mockAxios from "../../mockTests/DocumentFoldersMock";
it("fetches results for getAdminOrg", () => {
axios.get.mockImplementation(() =>
Promise.resolve({ data: { name: "GETtest" } })
);
const wrapper = mount(
<AppProviders>
<DocumentFolders />
</AppProviders>
);
const orgTitle = wrapper.find("#document-folders-h1");
expect(orgTitle.text()).toContain("GETtest Folders");
});
I am mocking the response data, however I am not sure how to run the setOrgTitle function which is called in the .then of my actual axios call. How can I do this from my mock axios call using my mock response?
The result of the Jest test says expected("GETtest Folders") received(" Folders") so I am pretty sure that I am either having an issue with asynchronicity or an issue calling the hook update.

Testing dispatched actions in Redux thunk with Jest

I'm quite new to Jest and admittedly am no expert at testing async code...
I have a simple Fetch helper I use:
export function fetchHelper(url, opts) {
return fetch(url, options)
.then((response) => {
if (response.ok) {
return Promise.resolve(response);
}
const error = new Error(response.statusText || response.status);
error.response = response;
return Promise.reject(error);
});
}
And implement it like so:
export function getSomeData() {
return (dispatch) => {
return fetchHelper('http://datasource.com/').then((res) => {
dispatch(setLoading(true));
return res.json();
}).then((data) => {
dispatch(setData(data));
dispatch(setLoading(false));
}).catch(() => {
dispatch(setFail());
dispatch(setLoading(false));
});
};
}
However I want to test that the correct dispatches are fired in the correct circumstances and in the correct order.
This used to be quite easy with a sinon.spy(), but I can't quite figure out how to replicate this in Jest. Ideally I'd like my test to look something like this:
expect(spy.args[0][0]).toBe({
type: SET_LOADING_STATE,
value: true,
});
expect(spy.args[1][0]).toBe({
type: SET_DATA,
value: {...},
});
Thanks in advance for any help or advice!
Answer as of January 2018
The redux docs have a great article on testing async action creators*:
For async action creators using Redux Thunk or other middleware, it's best to completely mock the Redux store for tests. You can apply the middleware to a mock store using redux-mock-store. You can also use fetch-mock to mock the HTTP requests.
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import * as actions from '../../actions/TodoActions'
import * as types from '../../constants/ActionTypes'
import fetchMock from 'fetch-mock'
import expect from 'expect' // You can use any testing library
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
describe('async actions', () => {
afterEach(() => {
fetchMock.reset()
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: [] })
return store.dispatch(actions.fetchTodos()).then(() => {
// return of async actions
expect(store.getActions()).toEqual(expectedActions)
})
})
})
Their approach is not to use jest (or sinon) to spy, but to use a mock store and assert the dispatched actions. This has the advantage of being able to handle thunks dispatching thunks, which can be very difficult to do with spies.
This is all straight from the docs, but let me know if you want me to create an example for your thunk.
* (this quote is no longer in the article as of January 2023 and the recommendations have changed dramatically, see comments on this answer for further info)
Answer as of January 2018
For async action creators using Redux Thunk or other middleware, it's best to completely mock the Redux store for tests. You can apply the middleware to a mock store using redux-mock-store. In order to mock the HTTP request, you can make use of nock.
According to redux-mock-store documentation, you will need to call store.getActions() at the end of the request to test asynchronous actions, you can configure your test like
mockStore(getState?: Object,Function) => store: Function Returns an
instance of the configured mock store. If you want to reset your store
after every test, you should call this function.
store.dispatch(action) => action Dispatches an action through the
mock store. The action will be stored in an array inside the instance
and executed.
store.getState() => state: Object Returns the state of the mock
store
store.getActions() => actions: Array Returns the actions of the mock
store
store.clearActions() Clears the stored actions
You can write the test action like
import nock from 'nock';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
//Configuring a mockStore
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
//Import your actions here
import {setLoading, setData, setFail} from '/path/to/actions';
test('test getSomeData', () => {
const store = mockStore({});
nock('http://datasource.com/', {
reqheaders // you can optionally pass the headers here
}).reply(200, yourMockResponseHere);
const expectedActions = [
setLoading(true),
setData(yourMockResponseHere),
setLoading(false)
];
const dispatchedStore = store.dispatch(
getSomeData()
);
return dispatchedStore.then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
P.S. Keep in ming that the mock-store does't update itself when the mocked action are fired and if you are depending on the updated data after the previous action to be used in the next action then you need to write your own instance of it like
const getMockStore = (actions) => {
//action returns the sequence of actions fired and
// hence you can return the store values based the action
if(typeof action[0] === 'undefined') {
return {
reducer: {isLoading: true}
}
} else {
// loop over the actions here and implement what you need just like reducer
}
}
and then configure the mockStore like
const store = mockStore(getMockStore);
Hope it helps. Also check this in redux documentation on testing async action creators
If you're mocking the dispatch function with jest.fn(), you can just access dispatch.mock.calls to get all the calls made to your stub.
const dispatch = jest.fn();
actions.yourAction()(dispatch);
expect(dispatch.mock.calls.length).toBe(1);
expect(dispatch.mock.calls[0]).toBe({
type: SET_DATA,
value: {...},
});
In my answer I am using axios instead of fetch as I don't have much experience on fetch promises, that should not matter to your question. I personally feel very comfortable with axios.
Look at the code sample that I am providing below:
// apiCalls.js
const fetchHelper = (url) => {
return axios.get(url);
}
import * as apiCalls from './apiCalls'
describe('getSomeData', () => {
it('should dispatch SET_LOADING_STATE on start of call', async () => {
spyOn(apiCalls, 'fetchHelper').and.returnValue(Promise.resolve());
const mockDispatch = jest.fn();
await getSomeData()(mockDispatch);
expect(mockDispatch).toHaveBeenCalledWith({
type: SET_LOADING_STATE,
value: true,
});
});
it('should dispatch SET_DATA action on successful api call', async () => {
spyOn(apiCalls, 'fetchHelper').and.returnValue(Promise.resolve());
const mockDispatch = jest.fn();
await getSomeData()(mockDispatch);
expect(mockDispatch).toHaveBeenCalledWith({
type: SET_DATA,
value: { ...},
});
});
it('should dispatch SET_FAIL action on failed api call', async () => {
spyOn(apiCalls, 'fetchHelper').and.returnValue(Promise.reject());
const mockDispatch = jest.fn();
await getSomeData()(mockDispatch);
expect(mockDispatch).toHaveBeenCalledWith({
type: SET_FAIL,
});
});
});
Here I am mocking the fetch helper to return Resolved promise to test success part and reject promise to test failed api call. You can pass arguments to them to validate on response also.
You can implement getSomeData like this:
const getSomeData = () => {
return (dispatch) => {
dispatch(setLoading(true));
return fetchHelper('http://datasource.com/')
.then(response => {
dispatch(setData(response.data));
dispatch(setLoading(false));
})
.catch(error => {
dispatch(setFail());
dispatch(setLoading(false));
})
}
}
I hope this solves your problem. Please comment, if you need any clarification.
P.S You can see by looking at above code why I prefer axios over fetch, saves you from lot of promise resolves! For further reading on it you can refer: https://medium.com/#thejasonfile/fetch-vs-axios-js-for-making-http-requests-2b261cdd3af5
Answer relevant as of January 2023
Many helpful answers here from 2018 are now outdated, the answer as of 2023 is to avoid mocking the store and instead use the real store, preferring integration tests (still using jest) over unit tests.
Some highlights from the updated, official Redux testing documentation:
Prefer writing integration tests with everything working together. For a React app using Redux, render a with a real store instance wrapping the components being tested. Interactions with the page being tested should use real Redux logic, with API calls mocked out so app code doesn't have to change, and assert that the UI is updated appropriately.
Do not try to mock selector functions or the React-Redux hooks! Mocking imports from libraries is fragile, and doesn't give you confidence that your actual app code is working.
It goes on to state how to achieve this, with the renderWithProvider function detailed here.
The article it links to for reasoning on this, includes the following quote, explaining the evolution of the thinking of redux testing best practices:
Our docs have always taught the "isolation" approach, and that does especially make sense for reducers and selectors. The "integration" approach was in a minority.
But, RTL and Kent C Dodds have drastically changed the mindset and approach for testing in the React ecosystem. The patterns I see now are about "integration"-style tests - large chunks of code, working together, as they'd be used in a real app.

Resources