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

Tests for Service Worker #1965

Merged
merged 23 commits into from
Nov 13, 2019
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
a0ca9fd
Added tests for setupWorkbox.js
revanth0212 Oct 29, 2019
dda0406
Added tests for registerRoutes.js
revanth0212 Oct 29, 2019
2a06bbc
Minor change.
revanth0212 Oct 29, 2019
016453c
Added tests for HTML route checking.
revanth0212 Oct 30, 2019
e243176
Added tests for isResizedCatalogImage in imageCacheHandler.js
revanth0212 Oct 30, 2019
5a32095
Merge remote-tracking branch 'origin/develop' into revanth/swTests
revanth0212 Nov 4, 2019
842aeed
Added tests for findSameOrLargerImage of imageCacheHandler.js
revanth0212 Nov 5, 2019
5717d4b
Minor change.
revanth0212 Nov 5, 2019
dda7740
Added tests for createCatalogCacheHandler
revanth0212 Nov 5, 2019
bac3e48
Another test for catalogCacheHandler.js
revanth0212 Nov 6, 2019
f0ba7b5
Merge remote-tracking branch 'origin/develop' into revanth/swTests
revanth0212 Nov 6, 2019
07e2745
Added tests for htmlHandler.js
revanth0212 Nov 6, 2019
8daefa6
Added tests for fetchDidSucceed function of cacheHTMLPlugin.
revanth0212 Nov 6, 2019
f84f0b4
Added tests for routeHandler.js
revanth0212 Nov 6, 2019
a18f183
Added named export __handlers__ for testing purposes.
revanth0212 Nov 6, 2019
174bed4
Added tests for registerMessageHandler
revanth0212 Nov 6, 2019
2fc1475
Added more tests for messageHandler.js
revanth0212 Nov 7, 2019
19278f5
Merge branch 'develop' into revanth/swTests
revanth0212 Nov 7, 2019
9a76a90
PR Changes.
revanth0212 Nov 12, 2019
88eefbd
Merge branch 'develop' into revanth/swTests
revanth0212 Nov 12, 2019
724e085
Minor.
revanth0212 Nov 12, 2019
6910521
Merge branch 'develop' into revanth/swTests
revanth0212 Nov 12, 2019
85ee41d
Merge branch 'develop' into revanth/swTests
dpatil-magento Nov 13, 2019
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
@@ -0,0 +1,57 @@
import { THIRTY_DAYS, CATALOG_CACHE_NAME } from '../../defaults';
import { createCatalogCacheHandler } from '../catalogCacheHandler';

function StaleWhileRevalidate(options = {}) {
this.cacheName = options.cacheName;
this.plugins = options.plugins;
}

function CacheableResponsePlugin(options = {}) {
this.statuses = options.statuses;
}

function ExpirationPlugin(options = {}) {
this.maxEntries = options.maxEntries;
this.maxAgeSeconds = options.maxAgeSeconds;
}

beforeAll(() => {
global.workbox = {
strategies: {
StaleWhileRevalidate
},
cacheableResponse: {
Plugin: CacheableResponsePlugin
},
expiration: {
Plugin: ExpirationPlugin
}
};
});

test('createCatalogCacheHandler should return an instance of workbox.strategies.StaleWhileRevalidate', () => {
expect(createCatalogCacheHandler()).toBeInstanceOf(StaleWhileRevalidate);
});

test('createCatalogCacheHandler should generate handler with cacheName set to the value of CATALOG_CACHE_NAME', () => {
expect(createCatalogCacheHandler().cacheName).toBe(CATALOG_CACHE_NAME);
});

test('createCatalogCacheHandler should generate handler with the exipiration plugin', () => {
const handler = createCatalogCacheHandler();
const [expirationPlugin] = handler.plugins.filter(
plugin => plugin instanceof ExpirationPlugin
);

expect(expirationPlugin.maxEntries).toBe(60);
expect(expirationPlugin.maxAgeSeconds).toBe(THIRTY_DAYS);
});

test('createCatalogCacheHandler should use the cacheable response plugin for statuses 0 and 200', () => {
const handler = createCatalogCacheHandler();
const [cacheableResponsePlugin] = handler.plugins.filter(
plugin => plugin instanceof CacheableResponsePlugin
);

expect(cacheableResponsePlugin.statuses).toEqual([0, 200]);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
jest.mock('../messageHandler');

import { HTML_UPDATE_AVAILABLE } from '@magento/venia-ui/lib/constants/swMessageTypes';

import { cacheHTMLPlugin } from '../htmlHandler';
import { sendMessageToWindow } from '../messageHandler';

const matchFn = jest.fn();

beforeAll(() => {
global.caches = {
match: matchFn
};
global.Request = function(url, { method, headers } = {}) {
this.url = url;
this.method = method;
this.headers = headers;
};
global.Response = function() {};
});

beforeEach(() => {
sendMessageToWindow.mockClear();
revanth0212 marked this conversation as resolved.
Show resolved Hide resolved
});

test('cacheHTMLPlugin should have cacheKeyWillBeUsed, requestWillFetch, fetchDidSucceed async functions implemented', () => {
matchFn.mockReturnValue(Promise.resolve(null));

expect(cacheHTMLPlugin).toHaveProperty('cacheKeyWillBeUsed');
expect(cacheHTMLPlugin).toHaveProperty('requestWillFetch');
expect(cacheHTMLPlugin).toHaveProperty('fetchDidSucceed');
revanth0212 marked this conversation as resolved.
Show resolved Hide resolved

expect(cacheHTMLPlugin.cacheKeyWillBeUsed).toBeInstanceOf(Function);
expect(cacheHTMLPlugin.requestWillFetch).toBeInstanceOf(Function);
expect(cacheHTMLPlugin.fetchDidSucceed).toBeInstanceOf(Function);

expect(cacheHTMLPlugin.cacheKeyWillBeUsed()).toBeInstanceOf(Promise);
expect(
cacheHTMLPlugin.requestWillFetch({
request: new Request('https://develop.pwa-venia.com/')
})
).toBeInstanceOf(Promise);
expect(
cacheHTMLPlugin.fetchDidSucceed({
request: new Request('https://develop.pwa-venia.com/'),
response: new Response()
})
).toBeInstanceOf(Promise);
});

test('cacheKeyWillBeUsed function should return a promise that resolves to /', async () => {
const response = await cacheHTMLPlugin.cacheKeyWillBeUsed();

expect(response).toBe('/');
});

test('requestWillFetch should return a new Request with url set to /', async () => {
const request = new Request('https://develop.pwa-venia.com/');
const response = await cacheHTMLPlugin.requestWillFetch({ request });

expect(response.url).not.toBe(request.url);
revanth0212 marked this conversation as resolved.
Show resolved Hide resolved
});

test('fetchDidSucceed should return the same response object given to it in params', async () => {
const request = new Request('https://develop.pwa-venia.com/');
const response = new Response();

const returnedResponse = await cacheHTMLPlugin.fetchDidSucceed({
request,
response
});

expect(returnedResponse).toBe(response);
});

test('fetchDidSucceed should not call sendMessageToWindow if the cache does not have a response for the url', async () => {
const request = new Request('https://develop.pwa-venia.com/');
const response = new Response();

await cacheHTMLPlugin.fetchDidSucceed({
request,
response
});

expect(sendMessageToWindow).not.toHaveBeenCalled();
});

test('fetchDidSucceed should call sendMessageToWindow if the response is different from what is in the cache', async () => {
/**
* Mocking Request to return different value when .text is called.
*/
global.Response.prototype.text = function() {
return Promise.resolve(
`Hey I am random text ${Math.random()
.toString()
.slice(2)}`
);
};
global.Response.prototype.clone = function() {
return new Response();
};
revanth0212 marked this conversation as resolved.
Show resolved Hide resolved

/**
* Mocking cache to have a response for 'https://develop.pwa-venia.com/'
*/
matchFn.mockReturnValue(Promise.resolve(new Response()));

const url = 'https://develop.pwa-venia.com/';
const request = new Request(url);
const response = new Response();

await cacheHTMLPlugin.fetchDidSucceed({ request, response });

expect(sendMessageToWindow).toHaveBeenCalledTimes(1);
expect(sendMessageToWindow).toHaveBeenCalledWith(HTML_UPDATE_AVAILABLE);
});

test('fetchDidSucceed should not call sendMessageToWindow if the response if same as that in the cache', async () => {
/**
* Mocking Request to return same value when .text is called.
*/
global.Response.prototype.text = function() {
return Promise.resolve('Hey I am same text');
};
global.Response.prototype.clone = function() {
return new Response();
};

/**
* Mocking cache to have a response for 'https://develop.pwa-venia.com/'
*/
matchFn.mockReturnValue(Promise.resolve(new Response()));

const url = 'https://develop.pwa-venia.com/';
const request = new Request(url);
const response = new Response();

await cacheHTMLPlugin.fetchDidSucceed({ request, response });

expect(sendMessageToWindow).not.toHaveBeenCalled();
});
revanth0212 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import {
isResizedCatalogImage,
findSameOrLargerImage
} from '../imageCacheHandler';

describe('Testing isResizedCatalogImage', () => {
const validCatalogImageURL =
'https://develop.pwa-venia.com/media/catalog/product/cache/6ff2031bbe5bd4726a5a91896c8bef9e/v/d/vd07-pe_main_2.jpg?auto=webp&format=pjpg&width=640&height=800';

const catalogImageURLWithInvalidWidth =
'https://develop.pwa-venia.com/media/catalog/product/cache/6ff2031bbe5bd4726a5a91896c8bef9e/v/d/vd07-pe_main_2.jpg?auto=webp&format=pjpg&width=640px&height=800px';

const invalidCatalogImageURL =
'https://develop.pwa-venia.com/product/cache/6ff2031bbe5bd4726a5a91896c8bef9e/v/d/vd07-pe_main_2.jpg?auto=webp&format=pjpg&width=640&height=800';

test('isResizedCatalogImage should return boolean', () => {
expect(
typeof isResizedCatalogImage({ url: new URL(validCatalogImageURL) })
).toBe('boolean');
});

test('isResizedCatalogImage should return true if the url provided is a valid catalog image url', () => {
expect(
isResizedCatalogImage({ url: new URL(validCatalogImageURL) })
).toBeTruthy();
});

test('isResizedCatalogImage should return false if /media/catalog is missing in the URL', () => {
expect(
isResizedCatalogImage({
url: new URL(invalidCatalogImageURL)
})
).toBeFalsy();
});

test('isResizedCatalogImage should return false if width search param is not valid in the URL', () => {
expect(
isResizedCatalogImage({
url: new URL(catalogImageURLWithInvalidWidth)
})
).toBeFalsy();
});

test('isResizedCatalogImage should throw error if url is missing in the function params', () => {
expect(() => isResizedCatalogImage()).toThrowError();
});
});

describe('Testing findSameOrLargerImage', () => {
beforeAll(() => {
global.caches = {
open: function() {
return Promise.resolve({
matchAll: function() {
return Promise.resolve([
{
url:
'https://develop.pwa-venia.com/media/catalog/v/s/vsk12-la_main_3.jpg?auto=webp&format=pjpg&width=160&height=200'
},
{
url:
'https://develop.pwa-venia.com/media/catalog/v/s/vsk12-la_main_3.jpg?auto=webp&format=pjpg&width=320&height=400'
},
{
url:
'https://develop.pwa-venia.com/media/catalog/v/s/vsk12-la_main_3.jpg?auto=webp&format=pjpg&width=1600&height=2000'
}
]);
}
});
}
};
});

test('Should return response from cache for same URL if available', async () => {
const expectedUrl =
'https://develop.pwa-venia.com/media/catalog/v/s/vsk12-la_main_3.jpg?auto=webp&format=pjpg&width=1600&height=2000';

const returnedResponse = await findSameOrLargerImage(
new URL(expectedUrl)
);

expect(returnedResponse.url).toBe(expectedUrl);
});

test('Should return the closest high resolution image response from cache for a given width', async () => {
const requestedUrl =
'https://develop.pwa-venia.com/media/catalog/v/s/vsk12-la_main_3.jpg?auto=webp&format=pjpg&width=800&height=1000';

const expectedUrl =
'https://develop.pwa-venia.com/media/catalog/v/s/vsk12-la_main_3.jpg?auto=webp&format=pjpg&width=1600&height=2000';

const returnedResponse = await findSameOrLargerImage(
new URL(requestedUrl)
);

expect(returnedResponse.url).toBe(expectedUrl);
});

test('Should return undefined if no closest high resolution image response is available in cache', async () => {
const requestedUrl =
'https://develop.pwa-venia.com/media/catalog/v/s/vsk12-la_main_3.jpg?auto=webp&format=pjpg&width=2400&height=3000';

const returnedResponse = await findSameOrLargerImage(
new URL(requestedUrl)
);

expect(returnedResponse).toBe(undefined);
});
});
Loading