diff --git a/packages/ajax/src/interceptors/cacheInterceptors.js b/packages/ajax/src/interceptors/cacheInterceptors.js index 06686dc76..1cb33883d 100644 --- a/packages/ajax/src/interceptors/cacheInterceptors.js +++ b/packages/ajax/src/interceptors/cacheInterceptors.js @@ -31,10 +31,10 @@ const isMethodSupported = (methods, method) => methods.includes(method.toLowerCa * @param {string[]|undefined} contentTypes * @returns {boolean} `true` if the contentTypes property is not an array, or if the value of the Content-Type header is in the array */ -const isResponseContentTypeSupported = (response, contentTypes) => { +export const isResponseContentTypeSupported = (response, contentTypes) => { if (!Array.isArray(contentTypes)) return true; - return contentTypes.includes(String(response.headers.get('Content-Type'))); + return !!contentTypes.find(ct => String(response.headers.get('Content-Type')).includes(ct)); }; /** diff --git a/packages/ajax/test/interceptors/cacheInterceptors.test.js b/packages/ajax/test/interceptors/cacheInterceptors.test.js index 6c9e43eb6..2d6862c2d 100644 --- a/packages/ajax/test/interceptors/cacheInterceptors.test.js +++ b/packages/ajax/test/interceptors/cacheInterceptors.test.js @@ -1,6 +1,7 @@ import { expect } from '@open-wc/testing'; import * as sinon from 'sinon'; import { Ajax, createCacheInterceptors } from '@lion/ajax'; +import { isResponseContentTypeSupported } from '../../src/interceptors/cacheInterceptors.js'; // TODO: these are private API? should they be exposed? if not why do we test them? import { extendCacheOptions, resetCacheSession, ajaxCache } from '../../src/cacheManager.js'; @@ -72,6 +73,36 @@ describe('cache interceptors', () => { sinon.restore(); }); + describe('isResponseContentTypeSupported', () => { + /** @type {Response} */ + let r; + + beforeEach(() => { + r = new Response(''); + }); + + it('matches default content type', () => { + r.headers.set('Content-Type', 'application/json'); + expect(isResponseContentTypeSupported(r, ['application/json'])).to.equal(true); + }); + + it('returns false when it doesnt match', () => { + r.headers.set('Content-Type', 'text/json'); + expect(isResponseContentTypeSupported(r, ['application/json'])).to.equal(false); + }); + + it('partially matches content type', () => { + r.headers.set('Content-Type', 'text/plain;charset=UTF-8;'); + expect(isResponseContentTypeSupported(r, ['text/plain'])).to.equal(true); + }); + + it('returns true if `contentTypes` is not an array', () => { + r.headers.set('Content-Type', 'foo'); + // @ts-ignore needed for test + expect(isResponseContentTypeSupported(r, 'string')).to.equal(true); + }); + }); + describe('Original ajax instance', () => { it('allows direct ajax calls without cache interceptors configured', async () => { await ajax.fetch('/test');