(Apollo client v3) useLazyQuery custom hook testing - unit-testing

I was struggling with a test issue for my custom useLazyQuery hook. My first test is passing but the second one is failing. What am doing wrong for the second test?
Here is the useLazyFetchCoin.tsx
export const useLazyFetchCoin = () => {
const [coins, setCoins] = useState<ICoin[]>([]);
useEffect(() => {
const coins = localStorage.getItem('coinsInfo');
if (coins) {
setCoins(JSON.parse(coins));
}
}, []);
const [getData, { loading, error }] = useLazyQuery(GET_COIN_PRICE_QUERY, {
fetchPolicy: 'network-only',
notifyOnNetworkStatusChange: true,
onCompleted: (data) => {
const hasSameCoin = coins.some((f) => f.id === data.markets[0]?.id);
if (data.markets.length && !hasSameCoin) {
const allCoins = [...coins, data.markets[0]];
setCoins(allCoins);
localStorage.setItem('coinsInfo', JSON.stringify(allCoins));
} else if (data.markets.length <= 0) {
alertNotification('Coin not found !', Notification.ERROR);
}
if (hasSameCoin) {
alertNotification('This coin already exists on your list !', Notification.WARNING);
}
}
});
return { coins, setCoins, getData, loading, error };
};
Here is the test file
describe('useLazyFetchCoin custom hook', () => {
const QueryMock = [
{
request: {
query: GET_COIN_PRICE_QUERY,
variables: { code: 'BNB' }
},
result: {
data: {
markets: [
{
id: 'binance_bnb_eur',
baseSymbol: 'BNB',
ticker: {
lastPrice: '414.90000000'
}
}
]
}
}
}
];
const QueryWrongCodeMock = [
{
request: {
query: GET_COIN_PRICE_QUERY,
variables: { code: 'asd' }
},
result: {
data: {
markets: []
}
}
}
];
function getHookWrapper(mocks: any, code: string) {
const wrapper = ({ children }: any) => (
<MockedProvider mocks={mocks} addTypename={false}>
{children}
</MockedProvider>
);
const { result, waitForNextUpdate } = renderHook(() => useLazyFetchCoin(), {
wrapper
});
expect(typeof result.current.coins).toBe('object');
expect(result.current.loading).toBeFalsy();
expect(result.current.error).toBeUndefined();
// call the lazy function
act(() => {
result.current.getData({
variables: { code }
});
});
return { result, waitForNextUpdate };
}
it('should return an array of coins', async () => {
// Working correctly
const { result, waitForNextUpdate } = getHookWrapper(QueryMock, 'BNB');
await waitForNextUpdate();
expect(result.current.loading).toBeFalsy();
expect(result.current.coins[0]).toEqual({
id: 'binance_bnb_eur',
baseSymbol: 'BNB',
ticker: {
lastPrice: '414.90000000'
}
});
});
it('should return an empty array when requesting a wrong code', async () => {
// Not working
const { result, waitForNextUpdate } = getHookWrapper(QueryWrongCodeMock, 'asd');
await waitForNextUpdate();
expect(result.current.loading).toBeFalsy();
expect(result.current.coins[0]).toEqual([]);
});
});
I got this error message for the second test.
Expected: []
Received: {"baseSymbol": "BNB", "id": "binance_bnb_eur", "ticker": {"lastPrice": "414.90000000"}}
I don't get it because I'm using different queries for each test.
Also, the second test should receive an empty array when you pass a wrong code such as 'asd'.
How can write a proper test for it?

I fixed the problem. When I was changing the order test, It worked correctly.
I added a clear mock function for it.
clear mock

Related

How can I mock a paginated GraphQL query?

I am using apollo/client and graphql-tools/mock to auto mock graphql queries and test React Native components that use them. My schema is generated from an introspection query created by graphql-codegen. For the most part, my queries are getting mocked by addMocksToSchema just fine. However I have a query that is not returning any mock data.
The query is paginated and doesn't follow the same structure of the examples in the docs (https://www.graphql-tools.com/docs/mocking). Instead of having a query with a node that has a field that is a connection type, the connection is returned from the query. This means I can't use relayStylePaginationMock to mock my function because the resolver argument of addMocksToSchema expects the nodes to be objects not functions(function is the return type of relayStylePaginationMock).
In the below code I have tried overriding the newsPost query with a resolver, but I can't figure out how to get the NewsPostEdges from the store and put them in my mock. Everything I have tried has broken the mock and caused it to return undefined for the whole mocked query.
Why does a paginated mock not work by default?
How can I mock this query?
Schema:
type Query {
newsPost: NewsPostConnection
}
type NewsPostConnection {
totalCount: Int
edges: [NewsPostEdge]!
pageInfo: PageInfo!
}
type NewsPostEdge {
node: NewsPostNode
cursor: String!
}
type NewsPostNode {
newsPostId: Int!
isPinned: Boolean!
label: String
title: String
content: String
postType: NewsPostType!
createdDate: DateTime
createdDateTime: String
creator: UserNode!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
endCursor: String
startCursor: String
}
News Posts query:
query NewsPosts(
$after: String
$first: Int
$newsPostId: Filter_ID
$sort: [NewsPostSortEnum]
$isPinned: Filter_Boolean
) {
newsPosts(
after: $after
first: $first
newsPostId: $newsPostId
sort: $sort
isPinned: $isPinned
) {
pageInfo {
hasNextPage
endCursor
}
edges {
post: node {
newsPostId
postType
isPinned
label
createdDateTime
creator {
initials
avatarUrl
displayName
}
content
}
}
}
}
newsPostsContent.test.tsx
import React from 'react';
import { waitFor } from '#testing-library/react-native';
import { PartialDeep } from 'type-fest';
import { faker } from '#faker-js/faker';
import { createFakeUser, render } from '#root/unit-tests/#util';
import { NewsPostNode, NewsPostType } from '#root/src/generated';
import NewsPostContent from '../NewsPostContent';
const mocks = {
NewsPostNode: (): PartialDeep<NewsPostNode> => {
const postId = faker.random.numeric(4);
const createdDate = faker.date.recent(10);
return {
postId,
isPinned: true,
label: 'test',
content: `<div><p>${faker.random.words(10)}</p></div>`,
postType: NewsPostType.Announcement,
createdDate: createdDate.toISOString(),
createdDateTime: createdDate.toISOString(),
};
},
UserNode: createUserPerson(),
};
describe('Dashboard News', () => {
it('renders dashboard news', async () => {
const { getByTestId, debug } = render(
<NewsPostContent />,
mocks,
);
await waitFor(() => [debug(), expect(getByTestId('newsPostContent:Card')).toBeDefined()]);
});
});
NewsPostsContetnt.tsx
const NewsPostContent = () => {
const [newsPostList, setNewsPostList] = useState<PartialDeep<NewsPostNode>[]>([])
const {
data,
loading,
refetch: refetchPosts,
} = useNewsPostsQuery({
variables: { first: MAX_POSTS, isPinned: true, sort: [PostSortEnum.CreatedDateDesc] },
});
console.log(data); // <-- returns undefined when mock breaks
useEffect(() => {
const newsPostEdges = data?.newsPosts?.edges ?? [];
const newsPostNodes = newsPostEdges.reduce((posts, newsPostNode) => {
if (newsPostNode?.post) {
posts.push(newsPostNode.post);
}
return posts;
}, [] as PartialDeep<NewsPostNode>[]);
setNewsPostList(newsPostNodes);
}, [data]);
return (
{<View>
// Component UI to render posts
</View>}
)
}
AutoMockedProvider.tsx
import React from 'react';
import { ApolloProvider, ApolloClient, InMemoryCache } from '#apollo/client';
import { buildClientSchema } from 'graphql';
import {
addMocksToSchema,
createMockStore,
IMocks,
IMockStore,
relayStylePaginationMock,
} from '#graphql-tools/mock';
import { SchemaLink } from '#apollo/client/link/schema';
import { faker } from '#faker-js/faker';
const introspectionResult = require('../../src/generated/introspection.json');
const defaultMocks = {
Date: () => faker.date.recent().toISOString(),
DateTime: () => faker.date.recent().toISOString(),
};
const resolvers = (store: IMockStore) => ({
Query: {
newsPosts: (root, { isPinned, after, first, postId, sort }) => {
return {
edges: (ref) => {
const connectionsRef = store.get('NewsPostConnection');
const edgesRef = store.get(connectionsRef, 'edges');
return edgesRef; // <-- this breaks the mock
},
pageInfo: {
endCursor: null,
hasNextPage: false,
},
};
},
},
});
const AutoMockedProvider = ({
mocks = {},
children,
}: React.PropsWithChildren<{ mocks?: IMocks }>) => {
const schema = buildClientSchema(introspectionResult);
const store = createMockStore({ mocks: { ...defaultMocks, ...mocks }, schema });
const schemaWithMocks = addMocksToSchema({
schema,
mocks: {
...defaultMocks,
...mocks,
},
resolvers,
preserveResolvers: false,
store,
});
const client = new ApolloClient({
link: new SchemaLink({ schema: schemaWithMocks }),
cache: new InMemoryCache(),
});
return <ApolloProvider client={client}>{children}</ApolloProvider>;
};
export default AutoMockedProvider;

How to fix Jest error : TypeError: $ is not a function

I am writing unit test cases for a Vue.js component.
When I am trying to shallowMount component using vue-test-util I get an error:
TypeError: $ is not a function at VueComponent.mounted
(src/components/gridComponent/index.vue:7579:7)
My code:
import $ from 'jquery';
global['$'] = global['jQuery'] = $;
import { shallowMount, createLocalVue } from '#vue/test-utils'
import gridComponent from '#/components/gridComponent/index'
describe('grid view component', () => {
it('has the expected HTML structure', async () => {
let wrapper = await shallowMount(gridComponent, {
stubs: ['GridLayout', 'GridItem'],
propsData: {componentsList}
})
expect(wrapper.element).toMatchSnapshot()
})
})
Below is the code of gridComponent:
import * as $ from 'jquery'
export default {
name: 'gridComponent',
components: { GridLayout, GridItem, DxpCommonModal },
props: ['componentsList'],
watch: {
componentsList: function (newVal, oldVal) {
// eslint-disable-next-line
this.matchingComponents = this.componentsList
}
},
data () {
return {
isDraggable: true,
isResizable: true
}
},
created () {
},
computed: {
...mapGetters(['getResources'])
},
mounted () {
$('#headerComponent').html(this.getSelectorHTML(this.siteDetails.header))
$('#footerComponent').html(this.getSelectorHTML(this.siteDetails.footer))
this.addHtmlOfComponentsInAPage()
},
destroyed () {
},
methods: {
addHtmlOfComponentsInAPage () {
this.selectedPage.Components.forEach((element, index) => {
$('#${index}').html(this.getSelectorHTML(this.selectedPage.Components[index]))
})
},
getSelectorHTML (component) {
const element = document.createElement(component.componentType)
element.setAttribute('content-id', new Date().getTime().toString())
if (!this.values && component.demoData) {
this.values = component.demoData
}
if (this.values) {
this.createMarkup(element, this.values)
this.values = ''
}
return element
}
}
}
Troubleshooting
In the component, try
const $ = require('jquery')
Put this before the usage in the method causing the error.
This will let you know if you are un-defining or redefining it somewhere.
Solution 2
You may need jsdom.
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM(`<!DOCTYPE html>`);
const $ = require('jquery')(window);

Saga unit test deepEqual returns false anyway

I am pretty much new with Redux-saga and working on unit test. API call function unit test code returns false even if it looks identical. What am I missing?
[Actions]
export const actions = {
readUsers: {
read: (data) => util.createAction('READ_USER', data),
request: () => util.createAction('READ_REQUEST'),
success: (data: any) => util.createAction('READ_SUCCESS', data),
failure: (error: any) => util.createAction('READ_FAILURE', error)
}
};
[Generator function]
export function* fetchUsers(action) {
yield put(actions.readUsers.request());
try {
let data = {id: action.payload.id, option: action.payload.option};
let response = yield call(API().getUsers, data);
if (response) {
yield put(actions.readUsers.success(response.users));
} else {
yield put(actions.readUsers.failure(response.error));
}
} catch (error) {
yield put(actions.readUsers.failure(error));
}
};
[Unit test]
const id = 'user-id';
const option = {};
const result = {users: []};
const action = {payload : {id, option}};
describe('user-saga', () => {
describe('fetchUsers', () => {
const generator = fetchUsers(action);
it('should return actions.readUsers.request()', () => {
assert.deepEqual(generator.next().value, put(actions.readUsers.request()));
}); // PASS
it('should return the Api.getUsers call', () => {
assert.equal(generator.next(result).value, call(Api().getUsers, action.payload));
}); // FAIL
it('should return actions.readUsers.success()', () => {
assert.deepEqual(generator.next(result).value, put(actions.readUsers.success(result)));
}); // FAIL
it('should be finished', () => {
assert.deepEqual(generator.next().done, true);
}); // PASS
})
});
[Test output]
First test passed.
Second test failed with this error message
AssertionError: { '##redux-saga/IO': true,
CALL: { context: null, fn: [Function: getUsers], args: [ [Object] ] } } deepEqual { '##redux-saga/IO': true,
CALL: { context: null, fn: [Function: getUsers], args: [ [Object] ] } }
Third test failed with this error message
AssertionError: undefined deepEqual { '##redux-saga/IO': true,
PUT: { channel: null,
action: { type: 'READ_SUCCESS', users: undefined } } }

Redux reducer unit test

And I'm trying to make unit-test for redux reducer. But i'm struggling with receiving the same expected and equal results.
const initState = {};
export default function (state = initState, action) {
const newState = { ...state };
switch (action.type) {
case CREATE_TYPE:
return {
...state,
[action.customType.id]: {
...action.customType
}
};
default:
return state;
}
}
My test. Seems that problem in customType: { id: 'test-id' }
describe('reducer', () => {
it('should return the initial state', () => {
const state = reducer(undefined, { type: 'unknown' });
expect(state).toEqual({});
});
it('should handle CREATE_TYPE', () => {
expect(reducer({ test: true }, {
type: CREATE_TYPE,
customType: { id: 'test-id' },
id: 'test-id'
})).toEqual({
'test-id': 'test-type',
'test': true
});
});
});
Often it helps to spell everything out.
That way you can clearly understand what your expected outcome needs to be.
it('should handle CREATE_TYPE', () => {
const initialState = { test: true };
const customType = { id: 'test-id' };
const action = {
type: CREATE_TYPE,
customType: customType,
id: customType.id
};
const result = reducer(initialState, action);
const expectedResult = {
test: true,
[customType.id]: customType
};
expect(result).toEqual(expectedResult);
});
It then becomes easier to see exactly where the issue lies.
You are exprecting back from your reducer :
{
...state,
[action.customType.id]: {
...action.customType
}
which if you send
{
type: CREATE_TYPE,
customType: { id: 'test-id' },
id: 'test-id'
}
Will equate itself to :
{
...state,
'test-id' : { id: 'test-id' }
}
and you are evaluating it equal to
{
...state,
'test-id': 'test-type'
}
I don't know how you are expecting to format your state via your reducer - but the way your reducer is set up now will not provide the state you are expecting. I don't know what you are expecting because i don't see the node or value 'test-type' anywhere else in your provided code. It looks like you just have some syntactical errors maybe?

Apollo: Update React Props on Subscription Update?

Looking at the Apollo docs example code for subscriptions, I am not yet seeing how to update the React props with the subscription results.
From http://dev.apollodata.com/react/subscriptions.html:
Here is a regular query:
import { CommentsPage } from './comments-page.js';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
const COMMENT_QUERY = gql`
query Comment($repoName: String!) {
entry(repoFullName: $repoName) {
comments {
id
content
}
}
}
`;
const withData = graphql(COMMENT_QUERY, {
name: 'comments',
options: ({ params }) => ({
variables: {
repoName: `${params.org}/${params.repoName}`
},
})
});
export const CommentsPageWithData = withData(CommentsPage);
Now, let’s add the subscription.
Note that this sample code appears to leave out this part of the props code for usual queries - from http://dev.apollodata.com/react/queries.html:
props: ({ ownProps, data: { loading, currentUser, refetch } }) => ({
userLoading: loading,
user: currentUser,
refetchUser: refetch,
}),
...which AFAIK is the correct way to update the data props on my React component and trigger a page refresh.
Here is the complete subscription code sample from http://dev.apollodata.com/react/subscriptions.html:
const withData = graphql(COMMENT_QUERY, {
name: 'comments',
options: ({ params }) => ({
variables: {
repoName: `${params.org}/${params.repoName}`
},
}),
props: props => {
return {
subscribeToNewComments: params => {
return props.comments.subscribeToMore({
document: COMMENTS_SUBSCRIPTION,
variables: {
repoName: params.repoFullName,
},
updateQuery: (prev, {subscriptionData}) => {
if (!subscriptionData.data) {
return prev;
}
const newFeedItem = subscriptionData.data.commentAdded;
return Object.assign({}, prev, {
entry: {
comments: [newFeedItem, ...prev.entry.comments]
}
});
}
});
}
};
},
});
How do I get the code shown here, to update the data props on my React component and trigger a page refresh, when the results come in from the non-subscription query COMMENT_QUERY?
Thanks to #neophi on the Apollo Slack for this answer!
const withDataAndSubscription = graphql(GETIMS_QUERY, {
options({toID}) {
console.log(GETIMS_QUERY);
const fromID = Meteor.userId();
return {
fetchPolicy: 'cache-and-network',
variables: {fromID: `${fromID}`, toID: `${toID}`}
};
}
,
props: props => {
return {
loading: props.data.loading,
instant_message: props.data.instant_message,
subscribeToMore: props.data.subscribeToMore,
subscribeToNewIMs: params => {
const fromID = Meteor.userId();
const toID = params.toID;
return props.data.subscribeToMore({
document: IM_SUBSCRIPTION_QUERY,
variables: {fromID: `${fromID}`, toID: `${toID}`},
updateQuery: (previousResult, {subscriptionData}) => {
if (!subscriptionData.data) {
return previousResult;
}
const newMsg = subscriptionData.data.createIM;
return update(previousResult, {
instant_message: {
$push: [newMsg],
},
});
}
});
}
};
},
})
;