mirror of
https://github.com/misskey-dev/misskey.git
synced 2024-12-12 08:20:52 +01:00
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": {
|
||||
"@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",
|
||||
|
|
44
test/api.ts
44
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');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
Loading…
Reference in a new issue