fix fetch mock (#9)
This commit is contained in:
parent
a4d5faa789
commit
460e23c2e7
2 changed files with 32 additions and 14 deletions
|
@ -18,8 +18,8 @@
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/jest": "^26.0.23",
|
"@types/jest": "^26.0.23",
|
||||||
"@types/node": "14.14.x",
|
"@types/node": "14.14.x",
|
||||||
"fetch-mock-jest": "^1.5.1",
|
|
||||||
"jest": "^26.6.3",
|
"jest": "^26.6.3",
|
||||||
|
"jest-fetch-mock": "^3.0.3",
|
||||||
"jest-websocket-mock": "^2.2.0",
|
"jest-websocket-mock": "^2.2.0",
|
||||||
"mock-socket": "^9.0.3",
|
"mock-socket": "^9.0.3",
|
||||||
"ts-jest": "^26.5.6",
|
"ts-jest": "^26.5.6",
|
||||||
|
|
40
test/api.ts
40
test/api.ts
|
@ -1,29 +1,47 @@
|
||||||
import fetchMock from 'fetch-mock-jest';
|
|
||||||
import { request } from '../src/api';
|
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', () => {
|
describe('API', () => {
|
||||||
test('success', async () => {
|
test('success', async () => {
|
||||||
fetchMock
|
fetchMock.resetMocks();
|
||||||
.post('https://misskey.test/api/i', (url, options) => {
|
fetchMock.mockResponse(async (req) => {
|
||||||
if (typeof options.body.i === 'string') {
|
const body = await req.json();
|
||||||
return {
|
if (req.method == 'POST' && req.url == 'https://misskey.test/api/i') {
|
||||||
body: {
|
if (typeof body.i != 'string') {
|
||||||
id: 'foo'
|
return { status: 400 };
|
||||||
}
|
}
|
||||||
};
|
return JSON.stringify({ id: 'foo' });
|
||||||
|
} else {
|
||||||
|
return { status: 404 };
|
||||||
}
|
}
|
||||||
return 400;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const res = await request('https://misskey.test', 'i', {}, 'TOKEN');
|
const res = await request('https://misskey.test', 'i', {}, 'TOKEN');
|
||||||
|
|
||||||
|
// validate response
|
||||||
expect(res).toEqual({
|
expect(res).toEqual({
|
||||||
id: 'foo'
|
id: 'foo'
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(fetchMock).toHaveLastFetched({
|
// validate fetch call
|
||||||
|
expect(getFetchCall(fetchMock.mock.calls[0])).toEqual({
|
||||||
url: 'https://misskey.test/api/i',
|
url: 'https://misskey.test/api/i',
|
||||||
|
method: 'POST',
|
||||||
body: { i: 'TOKEN' }
|
body: { i: 'TOKEN' }
|
||||||
}, 'post');
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
Loading…
Reference in a new issue