Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PWA-989: Real Data Wishlists and Wishlist Create #3041

Merged
merged 19 commits into from
Mar 23, 2021
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -350,8 +350,6 @@
"validation.mustBeChecked": "Doit être vérifié.",
"validation.validatePassword": "Un mot de passe doit contenir au moins 3 des éléments suivants: minuscules, majuscules, chiffres, caractères spéciaux.",
"wishlist.emptyListText": "Il n'y a actuellement aucun élément dans cette liste",
"wishlist.privateText": "Privée",
"wishlist.publicText": "Publique",

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

packages/extensions/venia-sample-language-packs/i18n/fr_FR.json

"wishlistItem.addToCart": "Ajouter au panier",
"wishlistItem.addToCartError": "Un problème est survenu. Veuillez actualiser et réessayer.",
"wishlistPage.disabledMessage": "Désolé, cette fonctionnalité a été désactivée.",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import React, { useEffect } from 'react';
import TestRenderer, { act } from 'react-test-renderer';
import { MockedProvider } from '@apollo/client/testing';
import { useApolloClient, InMemoryCache } from '@apollo/client';

import typePolicies from '../policies';

import { clearWishlistDataFromCache } from '../clearWishlistDataFromCache';

const log = jest.fn();

const Component = () => {
const client = useApolloClient();

const initialCacheData = Object.assign({}, client.cache.data.data);
log(initialCacheData);

const clear = async () => {
await clearWishlistDataFromCache(client);
const finalCacheData = Object.assign({}, client.cache.data.data);
log(finalCacheData);
};

useEffect(() => {
clear();
});
return <i />;
};

test('clears customer data from cache', async () => {
expect.assertions(3);
const cache = new InMemoryCache({
typePolicies
});

cache.restore({
Wishlist: {
id: '42',
name: 'Test'
},
ConfigurableWishlistItem: {
id: '42'
},
SimpleWishlistItem: {
id: '42'
},
AnotherCacheEntry: {
value: 'This entry should not get deleted'
}
});

await act(async () => {
TestRenderer.create(
<MockedProvider cache={cache}>
<Component />
</MockedProvider>
);
});

expect(log).toHaveBeenCalledTimes(2);

const initialCacheDataKeys = Object.keys(log.mock.calls[0][0]);
expect(initialCacheDataKeys).toEqual([
'Wishlist',
'ConfigurableWishlistItem',
'SimpleWishlistItem',
'AnotherCacheEntry'
]);

const finalCacheDataKeys = Object.keys(log.mock.calls[1][0]);
expect(finalCacheDataKeys).toEqual(['AnotherCacheEntry']);
});
13 changes: 13 additions & 0 deletions packages/peregrine/lib/Apollo/clearWishlistDataFromCache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { deleteCacheEntry } from './deleteCacheEntry';

/**
* Deletes references to Customer Wishlists from the apollo cache including *WishlistItem entries
*
* @param {ApolloClient} client
*/
export const clearWishlistDataFromCache = async client => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure about another utility function here, since I would consider wishlist part of customer data. Fine to keep this, but would be better to have clearCustomerDataFromCache call it.

Alternatively, there is a data security pattern we might want to establish. The clearCustomerDataFromCache will clear entities that start with Customer and I think we've just gotten lucky so far that they followed this pattern. You could instead define keyFields for Wishlist and WishlistItem, and this extra utility function wouldn't be needed.

Wishlist: {
    keyFields: ({ id }) => `CustomerWishlist:${id}`
},
WishlistItem: {
    keyFields: ({ id }) => `CustomerWishlistItem:${id}`
},

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed according your recommendations.
Thank you!

await deleteCacheEntry(client, key =>
key.match(/^\$?[a-zA-Z]+WishlistItem/)
);
await deleteCacheEntry(client, key => key.match(/^\$?Wishlist/));
};
2 changes: 2 additions & 0 deletions packages/peregrine/lib/store/actions/user/asyncActions.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import BrowserPersistence from '../../../util/simplePersistence';
import { clearCartDataFromCache } from '../../../Apollo/clearCartDataFromCache';
import { clearWishlistDataFromCache } from '../../../Apollo/clearWishlistDataFromCache';
import { clearCustomerDataFromCache } from '../../../Apollo/clearCustomerDataFromCache';
import { removeCart } from '../cart';
import { clearCheckoutDataFromStorage } from '../checkout';
Expand All @@ -26,6 +27,7 @@ export const signOut = (payload = {}) =>
await dispatch(actions.reset());
await clearCheckoutDataFromStorage();
await clearCartDataFromCache(apolloClient);
await clearWishlistDataFromCache(apolloClient);
await clearCustomerDataFromCache(apolloClient);

// Now that we're signed out, forget the old (customer) cart.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@

exports[`should return properly 1`] = `
Object {
"formErrors": Map {},
"handleCreateList": [Function],
"handleHideModal": [Function],
"handleShowModal": [Function],
"isModalOpen": false,
"loading": false,
"shouldRender": true,
}
`;
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Object {
"errors": Map {
"getCustomerWishlistQuery" => undefined,
},
"loading": undefined,
"wishlists": Array [],
}
`;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,57 +1,164 @@
import React from 'react';

import createTestInstance from '../../../util/createTestInstance';
import { MockedProvider } from '@apollo/client/testing';
import { renderHook, act } from '@testing-library/react-hooks';

import { useCreateWishlist } from '../useCreateWishlist';
import defaultOperations from '../createWishlist.gql';
import wishlistPageOperations from '../wishlistPage.gql';

const Component = props => {
const talonProps = useCreateWishlist(props);
jest.mock('@magento/peregrine/lib/context/app', () => {
const state = {};
const api = { actions: { setPageLoading: jest.fn() } };
const useAppContext = jest.fn(() => [state, api]);

return <i talonProps={talonProps} />;
};
return { useAppContext };
});

const getTalonProps = props => {
const tree = createTestInstance(<Component {...props} />);
const { root } = tree;
const { talonProps } = root.findByType('i').props;
const createWishlistVariables = {
name: 'Test WishList',
visibility: 'PUBLIC'
};

const update = newProps => {
tree.update(<Component {...{ ...props, ...newProps }} />);
let createWishlistMutationCalled = false;
let getCustomerWishlistsQueryCalled = false;
let getMultipleWishlistsEnabledQueryCalled = false;

const getCustomerWishlistsMock = {
request: {
query: wishlistPageOperations.getCustomerWishlistQuery
},
loading: false,
result: () => {
getCustomerWishlistsQueryCalled = true;
return {
data: {
customer: {
id: 'customerId',
wishlists: [
{
id: 42,
items_count: 0,
name: 'Test WishList',
visibility: 'PUBLIC',
sharing_code: 'code'
}
]
}
}
};
}
};

return root.findByType('i').props.talonProps;
};
const getMultipleWishlistsEnabledQueryMock = {
request: {
query: defaultOperations.getMultipleWishlistsEnabledQuery
},
loading: false,
result: () => {
getMultipleWishlistsEnabledQueryCalled = true;
return {
data: {
storeConfig: {
id: '42',
enable_multiple_wishlists: '1'
}
}
};
}
};

return { talonProps, tree, update };
const createWishlistMock = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How do you test the loading state of this mutation? I'm trying to do this in my PR but I'm having trouble...

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nvm, found it :D Just don't await the act'ed click.

request: {
query: defaultOperations.createWishlistMutation,
variables: { input: createWishlistVariables }
},
result: () => {
createWishlistMutationCalled = true;
return {
data: {
createWishlist: {
wishlist: {
id: '42'
}
}
}
};
}
};

test('should return properly', () => {
const { talonProps } = getTalonProps();
const renderHookWithProviders = ({
renderHookOptions = {},
mocks = [
createWishlistMock,
getCustomerWishlistsMock,
getMultipleWishlistsEnabledQueryMock
]
} = {}) => {
const wrapper = ({ children }) => (
<MockedProvider mocks={mocks} addTypename={false}>
{children}
</MockedProvider>
);

return renderHook(useCreateWishlist, { wrapper, ...renderHookOptions });
};

expect(talonProps).toMatchSnapshot();
test('should return properly', async () => {
const { result } = renderHookWithProviders();
await new Promise(resolve => setTimeout(resolve, 0));
expect(getMultipleWishlistsEnabledQueryCalled).toBe(true);
expect(result.current).toMatchSnapshot();
});

test('handleShowModal should set isModalOpen to true', () => {
const { talonProps, update } = getTalonProps();

talonProps.handleShowModal();
const { isModalOpen } = update();

expect(isModalOpen).toBeTruthy();
test('shouldRender is false when multiple wishlists disabled', async () => {
const multipleWishlistsDisabledMock = {
request: getMultipleWishlistsEnabledQueryMock.request,
result: {
data: { storeConfig: { id: '42', enable_multiple_wishlists: '0' } }
}
};
const { result } = renderHookWithProviders({
mocks: [
createWishlistMock,
getCustomerWishlistsMock,
multipleWishlistsDisabledMock
]
});
await new Promise(resolve => setTimeout(resolve, 0));
expect(result.current.shouldRender).toBe(false);
});

test('handleHideModal should set isModalOpen to false', () => {
const { talonProps, update } = getTalonProps();

talonProps.handleHideModal();
const { isModalOpen } = update();

expect(isModalOpen).toBeFalsy();
test('should return error', async () => {
const createWishlistErrorMock = {
request: createWishlistMock.request,
error: new Error('Only 5 wish list(s) can be created.')
};
const { result } = renderHookWithProviders({
mocks: [createWishlistErrorMock, getMultipleWishlistsEnabledQueryMock]
});
await act(() => result.current.handleCreateList(createWishlistVariables));
expect(
result.current.formErrors.get('createWishlistMutation')
).toMatchInlineSnapshot(`[Error: Only 5 wish list(s) can be created.]`);
});

test('handleCreateList should set isModalOpen to false', () => {
const { talonProps, update } = getTalonProps();
test('handleShowModal should set isModalOpen to true', async () => {
const { result } = renderHookWithProviders();
await act(() => result.current.handleShowModal());
expect(result.current.isModalOpen).toBe(true);
});

talonProps.handleCreateList();
const { isModalOpen } = update();
test('handleHideModal should set isModalOpen to false', async () => {
const { result } = renderHookWithProviders();
await act(() => result.current.handleHideModal());
expect(result.current.isModalOpen).toBe(false);
});

expect(isModalOpen).toBeFalsy();
test('handleCreateList should update cache and set isModalOpen to false', async () => {
const { result } = renderHookWithProviders();
await act(() => result.current.handleCreateList(createWishlistVariables));
expect(createWishlistMutationCalled).toBe(true);
expect(getCustomerWishlistsQueryCalled).toBe(true);
expect(result.current.isModalOpen).toBe(false);
});
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,13 @@ import { useQuery } from '@apollo/client';
jest.mock('react-router-dom', () => ({
useHistory: jest.fn()
}));
jest.mock('@apollo/client', () => ({
useQuery: jest.fn().mockReturnValue({})
}));
jest.mock('@apollo/client', () => {
const ApolloClient = jest.requireActual('@apollo/client');
return {
...ApolloClient,
useQuery: jest.fn().mockReturnValue({})
};
});
jest.mock('../../../context/user', () => ({
useUserContext: jest.fn().mockReturnValue([{ isSignedIn: true }])
}));
Expand All @@ -26,7 +30,9 @@ const Component = props => {
};

const props = {
queries: {}
queries: {
getCustomerWishlistQuery: {}
}
};

test('return correct shape', () => {
Expand Down
25 changes: 25 additions & 0 deletions packages/peregrine/lib/talons/WishlistPage/createWishlist.gql.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { gql } from '@apollo/client';

export const CREATE_WISHLIST = gql`
mutation createWishlist($input: CreateWishlistInput!) {
createWishlist(input: $input) {
wishlist {
id
}
}
}
`;

export const GET_MULTIPLE_WISHLISTS_ENABLED = gql`
query getMultipleWishlistsEnabled {
storeConfig {
id
enable_multiple_wishlists
}
}
`;

export default {
createWishlistMutation: CREATE_WISHLIST,
getMultipleWishlistsEnabledQuery: GET_MULTIPLE_WISHLISTS_ENABLED
};
Loading