Skip to content
This repository has been archived by the owner on Nov 27, 2024. It is now read-only.

Extend toHaveFetched test output to show options diff #32

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions __tests__/jest-extensions-post.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,25 @@ describe('jest extensions - post', () => {
headers: {
test: 'header',
},
body: {
test: {
testBody: 'value',
},
},
});
fetch('http://example.com/path', {
method: 'post',
headers: {
test: 'header',
},
body: {
test: {
value: 'value',
},
otherValue: {
value: 'value',
},
},
});
});
afterAll(() => fetch.reset());
Expand Down Expand Up @@ -80,6 +93,31 @@ describe('jest extensions - post', () => {
},
});
});

it('matches when using jest expect matchers', () => {
expect(fetch).toHavePosted('http://example.com/path', {
method: 'post',
headers: {
test: 'header',
},
body: expect.objectContaining({
test: {
value: 'value',
},
}),
});
expect(fetch).toHavePosted('end:path2', {
method: 'post',
headers: {
test: 'header',
},
body: {
test: {
testBody: expect.stringContaining('val'),
},
},
});
});
});
describe('toHaveLastPosted', () => {
beforeAll(() => {
Expand Down
2 changes: 1 addition & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { InspectionFilter, InspectionOptions, FetchMockStatic, MockCall, FetchMo

declare global {
namespace jest {
interface Matchers<R> {
interface Matchers<R, T> {
toHaveFetched(filter?: InspectionFilter, options?: InspectionOptions): R;
toHaveLastFetched(filter?: InspectionFilter, options?: InspectionOptions): R;
toHaveNthFetched(n: number, filter?: InspectionFilter, options?: InspectionOptions): R;
Expand Down
129 changes: 121 additions & 8 deletions jest-extensions.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
const { diff } = require('jest-diff');
const {
printReceived,
printExpected,
matcherHint,
} = require('jest-matcher-utils');
const { equals } = require('@jest/expect-utils');
const chalk = require('chalk');

const callsAreEqual = (c1, c2) => {
if (!c1 && !c2) return true;
if (!c1 || !c2) return false;
Expand All @@ -10,11 +19,122 @@ const callsAreEqual = (c1, c2) => {
return true;
};

const methodVerbMap = [
'Got:get',
'Posted:post',
'Put:put',
'Deleted:delete',
'FetchedHead:head',
'Patched:patch',
];

const parseOptionsBody = (call) => {
if (!call[1] || !call[1].body) return call[1];
let body;
try {
body = JSON.parse(call[1].body);
} catch (e) {
body = call[1].body;
}

return call[1] && call[1].method
? { ...call[1], body, method: call[1].method.toLowerCase() }
: { ...call[1], body };
};

const buildOptionsDiffMessage = (options) => (acc, call, index) => {
const parsedOptions = parseOptionsBody(call);
const diffString = diff(options, parsedOptions, {
expand: this.expand,
});
const header = `${acc}\n\n${chalk.dim(`- Call ${index + 1} (${call[0]})`)}`;

if (!diffString) return acc;
return diffString.includes('- Expect')
? `${header}\nDifference:\n\n${diffString}`
: `${header}\nExpected options: ${printExpected(options)}\n` +
`Received options: ${printReceived(parsedOptions)}`;
};

const methodlessExtensions = {
toHaveFetched: (fetchMock, url, options) => {
if (fetchMock.called(url, options)) {
return { pass: true };
}

if (fetchMock.called(url)) {
// check if body when accounting for jest matches
const matchesWithJestMatchers = fetchMock
.filterCalls(url)
.some(([, iteratedOptions]) => {
if (
iteratedOptions.method &&
options.method &&
iteratedOptions.method.toLowerCase() !==
options.method.toLowerCase()
)
return false;

try {
const parsedBody =
typeof iteratedOptions.body === 'string'
? JSON.parse(iteratedOptions.body)
: iteratedOptions.body;
if (!equals(parsedBody, options.body)) return false;
} catch (e) {
// eslint-disable-next-line no-console
console.error(
'Unable to parse body of mock call',
iteratedOptions.body
);
return false;
}

try {
const parsedHeaders =
typeof iteratedOptions.headers === 'string'
? JSON.parse(iteratedOptions.headers)
: iteratedOptions.headers;
if (!equals(parsedHeaders, options.headers)) return false;
} catch (e) {
// eslint-disable-next-line no-console
console.error(
'Unable to parse headers of mock call',
iteratedOptions.body
);
return false;
}

return true;
});

if (matchesWithJestMatchers) {
return { pass: true };
}

const method = options && options.method ? options.method : 'get';
const [humanVerb] = methodVerbMap
.find((verbMethod) => verbMethod.includes(`:${method}`))
.split(':');
const messageHeader = `${matcherHint(
`toHave${humanVerb}`,
undefined,
undefined,
options
)}\n\nNo ${method} request was made with the expected options.`;

const message = () => {
return fetchMock
.filterCalls(url)
.reduce(buildOptionsDiffMessage(options), messageHeader);
};

return {
pass: false,
message,
};
}

return {
pass: false,
message: () => `fetch should have been called with ${url}`,
Expand Down Expand Up @@ -83,14 +203,7 @@ expect.extend({
},
});

[
'Got:get',
'Posted:post',
'Put:put',
'Deleted:delete',
'FetchedHead:head',
'Patched:patch',
].forEach((verbs) => {
methodVerbMap.forEach((verbs) => {
const [humanVerb, method] = verbs.split(':');

const extensions = Object.entries(methodlessExtensions)
Expand Down
Loading