Debian Codegraph @

skins/Vector/tests/jest/fetch.test.js

raw symbols SCIP
1 /* global fetchMock */
2 const fetchJson = require( '../../resources/skins.vector.search/fetch.js' );
3 const jestFetchMock = require( 'jest-fetch-mock' );
4
5 const mockedRequests = !process.env.TEST_LIVE_REQUESTS;
6 const url = '//en.wikipedia.org/w/rest.php/v1/search/title?q=jfgkdajgioj&limit=10';
7
8 describe( 'abort() using AbortController', () => {
9 test( 'Aborting an unfinished request throws an AbortError', async () => {
10 expect.assertions( 1 );
11
12 const { abort, fetch } = fetchJson( url );
13
14 abort();
15
16 return fetch.catch( ( e ) => {
17 expect( e.name ).toStrictEqual( 'AbortError' );
18 } );
19 } );
20 } );
21
22 describe( 'fetch() using window.fetch', () => {
23 beforeAll( () => {
24 jestFetchMock.enableFetchMocks();
25 } );
26
27 afterAll( () => {
28 jestFetchMock.disableFetchMocks();
29 } );
30
31 beforeEach( () => {
32 fetchMock.resetMocks();
33 if ( !mockedRequests ) {
34 fetchMock.disableMocks();
35 }
36 fetchMock.mockIf( /^\/\/en.wikipedia.org\//, async ( req ) => {
37 if ( req.url === url ) {
38 return {
39 body: JSON.stringify( { pages: [] } ),
40 headers: {
41 'Content-Type': 'application/json'
42 }
43 };
44 } else {
45 return {
46 status: 404,
47 body: 'Page not found'
48 };
49 }
50 } );
51 } );
52
53 test( '200 without init param passed', async () => {
54 const { fetch } = fetchJson( url );
55 const json = await fetch;
56 const controller = new AbortController();
57 expect( json ).toStrictEqual( { pages: [] } );
58
59 if ( mockedRequests ) {
60 expect( fetchMock ).toHaveBeenCalledTimes( 1 );
61 expect( fetchMock ).toHaveBeenCalledWith( url, { signal: controller.signal } );
62 }
63 } );
64
65 test( '200 with init param passed', async () => {
66 const { fetch } = fetchJson( url, { mode: 'cors' } );
67 const json = await fetch;
68
69 expect( json ).toStrictEqual( { pages: [] } );
70
71 if ( mockedRequests ) {
72 expect( fetchMock ).toHaveBeenCalledTimes( 1 );
73 expect( fetchMock ).toHaveBeenCalledWith(
74 url,
75 expect.objectContaining( { mode: 'cors' } )
76 );
77 }
78 } );
79
80 test( '404 response', async () => {
81 expect.assertions( 1 );
82 const { fetch } = fetchJson( '//en.wikipedia.org/doesNotExist' );
83
84 await expect( fetch )
85 .rejects.toStrictEqual( 'Network request failed with HTTP code 404' );
86
87 if ( mockedRequests ) {
88 const controller = new AbortController();
89 expect.assertions( 3 );
90 expect( fetchMock ).toHaveBeenCalledTimes( 1 );
91 expect( fetchMock ).toHaveBeenCalledWith(
92 '//en.wikipedia.org/doesNotExist', { signal: controller.signal }
93 );
94 }
95 } );
96
97 } );