mocking a promise with shallow rendering using jest in react redux app - react-redux

I have looked at the following tutorials https://hackernoon.com/unit-testing-redux-connected-components-692fa3c4441c https://airbnb.io/enzyme/docs/api/shallow.html and tried to create a shallow rendered test of a component but i have actions being triggered on render which collect data and help render the component. how can i mock this?
tests/jest/containers/homecontent.js
import configureStore from 'redux-mock-store'
import { shallow } from 'enzyme';
import { HomeContent } from '../../../app/containers/home';
const passMetaBack = meta => {
this.setState({
title: 'test',
description: 'test'
});
};
// create any initial state needed
const initialState = {};
// here it is possible to pass in any middleware if needed into //configureStore
const mockStore = configureStore();
describe('Login Component', () => {
let wrapper;
let store;
beforeEach(() => {
// our mock login function to replace the one provided by mapDispatchToProps
const mockLoginfn = jest.fn();
//creates the store with any initial state or middleware needed
store = mockStore(initialState)
wrapper = shallow(<HomeContent isGuest={false} isReady={true} priv={{}} passMetaBack={passMetaBack} fetchContents={mockLoginfn} />)
});
it('+++ render the DUMB component', () => {
expect(wrapper.length).toEqual(1)
});
});
The error i get is
FAIL tests/jest/containers/homecontent.test.js
Login Component
✕ +++ render the DUMB component (25ms)
● Login Component › +++ render the DUMB component
TypeError: Cannot read property 'then' of undefined
38 | if(this.props.isReady && this.props.priv != undefined){
39 | let self = this;
> 40 | this.props.fetchContents()
41 | .then(response => {
42 | let data = response.payload.data;
43 | if (data.header.error) {
at HomeContent.initData (app/containers/home.js:40:7)
at HomeContent.render (app/containers/home.js:71:12)
at ReactShallowRenderer._mountClassComponent (node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:195:37)
at ReactShallowRenderer.render (node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:143:14)
at node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:287:35
at withSetStateAllowed (node_modules/enzyme-adapter-utils/build/Utils.js:103:16)
at Object.render (node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:286:68)
at new ShallowWrapper (node_modules/enzyme/build/ShallowWrapper.js:119:22)
at shallow (node_modules/enzyme/build/shallow.js:19:10)
at Object.<anonymous> (tests/jest/containers/homecontent.test.js:24:19)
● Login Component › +++ render the DUMB component
TypeError: Cannot read property 'length' of undefined
26 |
27 | it('+++ render the DUMB component', () => {
> 28 | expect(wrapper.length).toEqual(1)
29 | });
30 | });
31 |
at Object.<anonymous> (tests/jest/containers/homecontent.test.js:28:24)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 2.218s
Ran all test suites matching /tests\/jest\/containers\/homecontent.test.js/i.
this.props.fetchContents() comes in from an action on the component

mockLoginfn is used as this.props.fetchContents in the component. fetchContents is a function that returns a promise, whereas mockLoginfn is a jest mock function that doesn't return anything.
So, you need to provide a mock implementation for the mockLoginfn so it behaves like a promise. For example (using the code snippet above):
const mockLoginfn = jest.fn();
mockLoginfn.mockImplementation(() => Promise.resolve({
payload: {
data: {
header: {
error: 'some error'
}
}
}
}));

Related

How to test Vue3 and intertia with jest

In a Laravel + Vue3 + Inertia project which setup using Laravel Mix, how we can create front-end tests?
Especially, I have no idea how to handle Inertia's Share Data, usePage() and useForm methods?
The first error I'm facing is:
TypeError: Cannot read properties of undefined (reading 'someSharedData')
2 |
3 | export const handleSometing = (something) =>
> 4 | usePage().props.value.someSharedData
| ^
5 | ...
6 | )
After googling some useless hours and finding nothing to this exact problem, I've found this solution.
The key was in Jest Partial Mocking!
You can mock useForm, usePage, and then Shared Data using Jest Partial Mocking.
After setup the vue-test-util, I have created this test file and it was working like a charm.
In the below example, the i18n is mocked using the config object of the vue-test-utils.
The Inertia's methods are mocked by jest.mock().
import { config, shallowMount } from '#vue/test-utils'
import Dashboard from '#/Components/ExampleComponent'
config.global.mocks = {
$t: () => '',
}
jest.mock('#inertiajs/inertia-vue3', () => ({
__esModule: true,
...jest.requireActual('#inertiajs/inertia-vue3'), // Keep the rest of Inertia untouched!
useForm: () => ({
/** Return what you need **/
/** Don't forget to mock post, put, ... methods **/
}),
usePage: () => ({
props: {
value: {
someSharedData: 'something',
},
},
}),
}))
test('Render ExampleComponent without crash', () => {
const wrapper = shallowMount(ExampleComponent, {
props: {
otherPageProps: {}
}
})
expect(wrapper.text()).toContain('Hi! I am ExampleComponent.')
})

how to jest test connected component which has api calls in componentDidMount

I am trying to test a connected component but it does not seem to make the api calls in the componentDidMount function. I need it to make the api calls so i can test the how this component woudl render depending on the values returned from api calls. api calls are made by axios using redux actions. everything stored in redux.
here is my test
it('should dispatch an action on mount', () => {
const component = shallow(
<ProcessingStatus store={store}/>
);
const didMount = jest.spyOn(component, 'componentDidMount');
expect(didMount).toHaveBeenCalledTimes(1);
//console.log(component.html())
expect(store.dispatch).toHaveBeenCalledTimes(3);
});
this is the componentDidMount in my component
componentDidMount() {
const {
matches: { params: { id } },
processingStatus,
securityStatus,
routingStatus,
soxStatus,
remedyStatus,
user: {
priv: {
my_sox_requests,
view_remedy
}
}
} = this.props;
let params = 'id=' + id;
if(processingStatus !== undefined){
processingStatus(params)
.catch(thrown => {
console.log(thrown);
});
}
if(securityStatus !== undefined){
securityStatus(params)
.catch(thrown => {
console.log(thrown);
});
}
if(routingStatus !== undefined){
routingStatus(params)
.catch(thrown => {
console.log(thrown);
});
}
if(my_sox_requests && my_sox_requests === 'on' && soxStatus !== undefined){
soxStatus(params)
.catch(thrown => {
console.log(thrown);
});
}
if(view_remedy && view_remedy === 'on' && remedyStatus !== undefined){
remedyStatus(params)
.catch(thrown => {
console.log(thrown);
});
}
}
Error i get is
FAIL tests/jest/components/common/ProcessingStatus/index.test.js
<ProcessingStatus />
✓ should render with given state from Redux store (90ms)
✕ should dispatch an action on mount (7ms)
● <ProcessingStatus /> › should dispatch an action on mount
Cannot spy the componentDidMount property because it is not a function; undefined given instead
85 | <ProcessingStatus store={store}/>
86 | );
> 87 | const didMount = jest.spyOn(component, 'componentDidMount');
| ^
88 | expect(didMount).toHaveBeenCalledTimes(1);
89 |
90 | //console.log(component.html())
at ModuleMockerClass.spyOn (node_modules/jest-mock/build/index.js:841:15)
at Object.<anonymous> (tests/jest/components/common/ProcessingStatus/index.test.js:87:31)
I tried with const didMount = jest.spyOn(ProcessingStatus.prototype, 'componentDidMount'); and error i get is
● <ProcessingStatus /> › should dispatch an action on mount
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
85 | );
86 | const didMount = jest.spyOn(ProcessingStatus.prototype, 'componentDidMount');
> 87 | expect(didMount).toHaveBeenCalledTimes(1);
| ^
88 |
89 | //console.log(component.html())
90 | expect(store.dispatch).toHaveBeenCalledTimes(3);
I managed to test didmount being called but not sure how to check if the api calls have been made.
it('should run componentDidMount', () => {
spy = jest.spyOn(ProcessingStatus.prototype, 'componentDidMount');
component = mount(
<ProcessingStatus store={store}/>
);
expect(spy).toHaveBeenCalledTimes(1);
});
I've been searching a similar question here and found out that you have some order errors:
you should set the spyOn componentDidMount before the shallow(Component)
you should ask for Component.prototype.componentDidMount was called after shallow component
jest.spyOn(Component.prototype, 'componentDidMount')
shallow(<Component/>)
expect(Component.prototype.componentDidMount).toHaveBeenCalled();
if the component expect to receive props functions that are going to be called inside the componentDidMount, you should add them when shallow Component like
const mockExpectedFunction= jest.fn()
shallow(<Component expectedFunction={mockExpectedFunction} />

Export componenent after ajax call finishes in React

I want to export a component after the ajax call finishes. Here is the below code, the output of below code is
exporting 1
exporting 3
exporting 4
exporting 2
But I want to execute it sequentially, My desired output is
exporting 1
exporting 2
exporting 3
exporting 4
import appLocaleData from "react-intl/locale-data/en";
import enMessages from "../locales/en_US.json";
import config from "config";
const lang = new Object();
console.log( " exporting 1" );
fetch(`${config.api.languageUrl}english.json`, {
method: "GET",
headers: {
"Content-Type": "application/octet-stream"
}
})
.then(res => res.json())
.then(json => {
Object.assign(lang, json);
console.log("json->", json);
console.log("lang->", lang);
console.log(lang._VIEW);
console.log( "exporting 2" );
});
console.log( "exporting 3" );
const EnLang = {
messages: {
...lang
},
locale: "en-US",
data: appLocaleData
};
console.log( "exporting 4" );
export default EnLang;
Is there anyway in react, I can perform this ?
Thanks,
No, there is no such thing as an asynchronous export in javascript. If you can be more clear about what you are trying to accomplish I might be able to suggest a possible approach, but as is I don't even understand how this has anything to do with React specifically
EDIT based on OP's reply:
try something like this...
export const LocalsContext = React.createContext([]);
const App = () => {
...
const [locals, setLocals] = useState([]);
useEffect(() => {
fetch(...)
.then(...)
.then(localsList => setLocals(localsList)
}, []);
return (
<LocalsContext.Provider value={locals}>
...
</LocalsContext.Provider>
)
}
export default App
and then in any component anywhere within your app you can access the locals like so:
const MyComponent = () => {
/*
* will re-render whenever the locals updates,
* i.e., will render once with [] as the value, then once the
* data is fetched it will render again with the actual locals value
*/
const locals = useContext(LocalsContext);
return <div>some component</div>
}

verify loading indicator shows with cypress

I have the following spec:
context('Contact update', () => {
it.only('Can update contact', () => {
const address = 'new address 123'
const cardId = 'c2card-38AF429999C93B5DC844D86381734E62'
cy.viewport('macbook-15')
cy.authVisit('/contact/list')
cy.getByTestId('open-doc-Aaron Dolney-0').click()
cy.get('[name="physicaladdress"').type(`{selectall}{backspace}${address}`)
cy.getByTestId(cardId, 'save-button').click()
cy.getByTestId(cardId, 'loading')
cy.get('[name="physicaladdress"').should('have.value', address)
})
})
getByTestId is a command I wrote to reduce some boilerplate:
Cypress.Commands.add('getByTestId', (...ids) => {
const id = ids.map(id => `[data-testid="${id}"]`).join(' ')
return cy.get(id)
})
When I run this with anything other than cypress open, it fails on getting the loading indicator. I'm thinking my test endpoint is responding too fast and toggling the loading indicator too quickly.
Is there a better, more consistent, way to verify the loading indicator shows?
I was struggling with this as well since I wanted to make sure the loading indicator was showing so I had to get a bit crafty. I found that cy.route() has an onRequest option and that ended up being just what I needed.
https://docs.cypress.io/api/commands/route.html#Options
cy.server();
// Verify that the loading indicator is shown before the request finishes
cy.route({
url: url_of_request_that_triggers_loading,
onRequest: () => {
cy.getByTestId(cardId, 'loading');
},
});
With this implementation we run the loading expectation before the request finishes and before the loading indicator disappears.
I found quite a reliable although bit complicated solution to that. I uses jQuery Deferred (bundled with cypress) along with internal cypress state (via aliases).
For extensive testing of intermediate states it works great.
/**
* Workaround for delegating {#link Cypress.Chainable['intercept']} - internal Method type is
* not exported and thus delegating it is difficult. It's also difficult to extract it from
* the function type because of overloads. If any more methods are needed, feel free
* to add them here
*/
type Method = 'GET' | 'POST' | 'PATCH' | 'DELETE';
// extend this type if you need more flexibility
export interface ResponseStub {
status: number;
response: unknown;
}
/**
* Deferred needs to be wrapped in an object because wrap() acts differently on promise-like args
*/
type InertDeferred = { deferred: Deferred<Partial<ResponseStub> | undefined> };
const deferredAlias = (aliasId: string): string => `${aliasId}Deferred`;
const deferredAliasSelector = (aliasId: string): string => `#${deferredAlias(aliasId)}`;
export const deferredRequestCommand = (
method: Method,
url: string,
aliasId: string,
fixture: string,
): void => {
const deferred: InertDeferred['deferred'] = Cypress.$.Deferred();
cy.wrap({ deferred }).as(deferredAlias(aliasId));
cy.fixture(fixture).then((data) => {
cy.intercept(method, url, (req) => {
deferred
.then((stub) => {
req.reply(stub?.status || 200, stub?.response || data);
});
return deferred.promise();
});
});
};
export const resolveDeferredRequestCommand = (
aliasId: string,
stub: Partial<ResponseStub> = undefined,
): void => {
cy.get<InertDeferred>(deferredAliasSelector(aliasId))
.invoke('deferred.resolve', stub);
};

How to refetch a query when a new subscription arrives in react-apollo

I was wondering if there's an elegant way to trigger the refetch of a query in react-apollo when a subscription receives new data (The data is not important here and will be the same as previous one). I just use subscription here as a notification trigger that tells Query to refetch.
I tried both using Subscription component and subscribeToMore to call "refetch" method in Query's child component but both methods cause infinite re-fetches.
NOTE: I'm using react-apollo v2.1.3 and apollo-client v2.3.5
here's the simplified version of code
<Query
query={GET_QUERY}
variables={{ blah: 'test' }}
>
{({ data, refetch }) => (
<CustomComponent data={data} />
//put subscription here? It'll cause infinite re-rendering/refetch loop
)}
<Query>
Finally I figured it out myself with the inspiration from Pedro's answer.
Thoughts: the problem I'm facing is that I want to call Query's refetch method in Subscription, however, both Query and Subscription components can only be accessed in render method. That is the root cause of infinite refetch/re-rendering. To solve the problem, we need to move the subscription logic out of render method and put it somewhere in a lifecycle method (i.e. componentDidMount) where it won't be called again after a refetch is triggered. Then I decided to use graphql hoc instead of Query component so that I can inject props like refetch, subscribeToMore at the top level of my component, which makes them accessible from any life cycle methods.
Code sample (simplified version):
class CustomComponent extends React.Component {
componentDidMount() {
const { data: { refetch, subscribeToMore }} = this.props;
this.unsubscribe = subscribeToMore({
document: <SUBSCRIBE_GRAPHQL>,
variables: { test: 'blah' },
updateQuery: (prev) => {
refetch();
return prev;
},
});
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const { data: queryResults, loading, error } } = this.props;
if (loading || error) return null;
return <WhatEverYouWant with={queryResults} />
}
}
export default graphql(GET_QUERY)(CustomComponent);
It's possible if you use componentDidMount and componentDidUpdate in the component rendered by the Subscription render props function.
The example uses recompose higher order components to avoid too much boilerplating. Would look something like:
/*
* Component rendered when there's data from subscription
*/
export const SubscriptionHandler = compose(
// This would be the query you want to refetch
graphql(QUERY_GQL, {
name: 'queryName'
}),
lifecycle({
refetchQuery() {
// condition to refetch based on subscription data received
if (this.props.data) {
this.props.queryName.refetch()
}
},
componentDidMount() {
this.refetchQuery();
},
componentDidUpdate() {
this.refetchQuery();
}
})
)(UIComponent);
/*
* Component that creates the subscription operation
*/
const Subscriber = ({ username }) => {
return (
<Subscription
subscription={SUBSCRIPTION_GQL}
variables={{ ...variables }}
>
{({ data, loading, error }) => {
if (loading || error) {
return null;
}
return <SubscriptionHandler data={data} />;
}}
</Subscription>
);
});
Another way of accomplishing this while totally separating Query and Subscription components, avoiding loops on re-rendering is using Apollo Automatic Cache updates:
+------------------------------------------+
| |
+----------->| Apollo Store |
| | |
| +------------------------------+-----------+
+ |
client.query |
^ +-----------------+ +---------v-----------+
| | | | |
| | Subscription | | Query |
| | | | |
| | | | +-----------------+ |
| | renderNothing | | | | |
+------------+ | | | Component | |
| | | | | |
| | | +-----------------+ |
| | | |
+-----------------+ +---------------------+
const Component =() => (
<div>
<Subscriber />
<QueryComponent />
</div>
)
/*
* Component that only renders Query data
* updated automatically on query cache updates thanks to
* apollo automatic cache updates
*/
const QueryComponent = graphql(QUERY_GQL, {
name: 'queryName'
})(() => {
return (
<JSX />
);
});
/*
* Component that creates the subscription operation
*/
const Subscriber = ({ username }) => {
return (
<Subscription
subscription={SUBSCRIPTION_GQL}
variables={{ ...variables }}
>
{({ data, loading, error }) => {
if (loading || error) {
return null;
}
return <SubscriptionHandler data={data} />;
}}
</Subscription>
);
});
/*
* Component rendered when there's data from subscription
*/
const SubscriptionHandler = compose(
// This would be the query you want to refetch
lifecycle({
refetchQuery() {
// condition to refetch based on subscription data received
if (this.props.data) {
var variables = {
...this.props.data // if you need subscription data for the variables
};
// Fetch the query, will automatically update the cache
// and cause QueryComponent re-render
this.client.query(QUERY_GQL, {
variables: {
...variables
}
});
}
},
componentDidMount() {
this.refetchQuery();
},
componentDidUpdate() {
this.refetchQuery();
}
}),
renderNothing
)();
/*
* Component that creates the subscription operation
*/
const Subscriber = ({ username }) => {
return (
<Subscription
subscription={SUBSCRIPTION_GQL}
variables={{ ...variables }}
>
{({ data, loading, error }) => {
if (loading || error) {
return null;
}
return <SubscriptionHandler data={data} />;
}}
</Subscription>
);
});
Note:
compose and lifecycle are recompose methods that enable easier a cleaner higher order composition.

Resources