From 460e23c2e74964c478cb89da4a80161b17772f6c Mon Sep 17 00:00:00 2001 From: marihachi Date: Sun, 16 May 2021 11:11:05 +0900 Subject: [PATCH] fix fetch mock (#9) --- package.json | 2 +- test/api.ts | 44 +++++++++++++++++++++++++++++++------------- 2 files changed, 32 insertions(+), 14 deletions(-) diff --git a/package.json b/package.json index 73bfb5e935..aac498417b 100644 --- a/package.json +++ b/package.json @@ -18,8 +18,8 @@ "devDependencies": { "@types/jest": "^26.0.23", "@types/node": "14.14.x", - "fetch-mock-jest": "^1.5.1", "jest": "^26.6.3", + "jest-fetch-mock": "^3.0.3", "jest-websocket-mock": "^2.2.0", "mock-socket": "^9.0.3", "ts-jest": "^26.5.6", diff --git a/test/api.ts b/test/api.ts index cbb8e5736e..499c133cad 100644 --- a/test/api.ts +++ b/test/api.ts @@ -1,29 +1,47 @@ -import fetchMock from 'fetch-mock-jest'; import { request } from '../src/api'; +import { enableFetchMocks } from 'jest-fetch-mock'; + +enableFetchMocks(); + +function getFetchCall(call: any[]) { + const { body, method } = call[1]; + if (body != null && typeof body != 'string') { + throw new Error('invalid body'); + } + return { + url: call[0], + method: method, + body: JSON.parse(body as any) + }; +} describe('API', () => { test('success', async () => { - fetchMock - .post('https://misskey.test/api/i', (url, options) => { - if (typeof options.body.i === 'string') { - return { - body: { - id: 'foo' - } - }; + fetchMock.resetMocks(); + fetchMock.mockResponse(async (req) => { + const body = await req.json(); + if (req.method == 'POST' && req.url == 'https://misskey.test/api/i') { + if (typeof body.i != 'string') { + return { status: 400 }; } - return 400; - }); + return JSON.stringify({ id: 'foo' }); + } else { + return { status: 404 }; + } + }); const res = await request('https://misskey.test', 'i', {}, 'TOKEN'); + // validate response expect(res).toEqual({ id: 'foo' }); - expect(fetchMock).toHaveLastFetched({ + // validate fetch call + expect(getFetchCall(fetchMock.mock.calls[0])).toEqual({ url: 'https://misskey.test/api/i', + method: 'POST', body: { i: 'TOKEN' } - }, 'post'); + }); }); });