|
| 1 | +import { rest } from 'msw'; |
1 | 2 | import { createClient } from '../src/createClient'; |
| 3 | +import { testBaseUrl } from './mocks/handlers'; |
| 4 | +import { server } from './mocks/server'; |
2 | 5 |
|
3 | 6 | describe('createClient', () => { |
4 | 7 | test('Functions is generated to request the API', () => { |
@@ -41,4 +44,60 @@ describe('createClient', () => { |
41 | 44 | createClient({ serviceDomain: 'foo', apiKey: 10 }) |
42 | 45 | ).toThrowError(new Error('parameter is not string')); |
43 | 46 | }); |
| 47 | + |
| 48 | + describe('Throws an error when response.ok is false', () => { |
| 49 | + test('If there is a message', () => { |
| 50 | + server.use( |
| 51 | + rest.get(`${testBaseUrl}/list-type`, async (_, res, ctx) => { |
| 52 | + return res( |
| 53 | + ctx.status(401), |
| 54 | + ctx.json({ message: 'X-MICROCMS-KEY header is invalid.' }) |
| 55 | + ); |
| 56 | + }) |
| 57 | + ); |
| 58 | + const client = createClient({ |
| 59 | + serviceDomain: 'serviceDomain', |
| 60 | + apiKey: 'apiKey', |
| 61 | + }); |
| 62 | + |
| 63 | + expect(client.get({ endpoint: 'list-type' })).rejects.toThrowError( |
| 64 | + new Error( |
| 65 | + 'fetch API response status: 401\n message is `X-MICROCMS-KEY header is invalid.`' |
| 66 | + ) |
| 67 | + ); |
| 68 | + }); |
| 69 | + test('If there is no message', () => { |
| 70 | + server.use( |
| 71 | + rest.get(`${testBaseUrl}/list-type`, async (_, res, ctx) => { |
| 72 | + return res(ctx.status(404)); |
| 73 | + }) |
| 74 | + ); |
| 75 | + const client = createClient({ |
| 76 | + serviceDomain: 'serviceDomain', |
| 77 | + apiKey: 'apiKey', |
| 78 | + }); |
| 79 | + |
| 80 | + expect(client.get({ endpoint: 'list-type' })).rejects.toThrowError( |
| 81 | + new Error('fetch API response status: 404') |
| 82 | + ); |
| 83 | + }); |
| 84 | + }); |
| 85 | + |
| 86 | + test('Throws an error in the event of a network error.', () => { |
| 87 | + server.use( |
| 88 | + rest.get(`${testBaseUrl}/list-type`, async (_, res) => { |
| 89 | + return res.networkError('Failed to fetch'); |
| 90 | + }) |
| 91 | + ); |
| 92 | + const client = createClient({ |
| 93 | + serviceDomain: 'serviceDomain', |
| 94 | + apiKey: 'apiKey', |
| 95 | + }); |
| 96 | + |
| 97 | + expect(client.get({ endpoint: 'list-type' })).rejects.toThrowError( |
| 98 | + new Error( |
| 99 | + 'Network Error.\n Details: FetchError: request to https://servicedomain.microcms.io/api/v1/list-type failed, reason: Failed to fetch' |
| 100 | + ) |
| 101 | + ); |
| 102 | + }); |
44 | 103 | }); |
0 commit comments