Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add expected/received variables to 'No more mocked responses' error message #8340

Merged
Merged
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,8 @@ describe('General use', () => {
}

const variables2 = {
username: 'other_user'
username: 'other_user',
age: undefined
};

render(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ exports[`General use should error if the query in the mock and component do not
__typename
}
}
, variables: {"username":"mock_username"}]

Expected variables: {"username":"mock_username"}
]
`;

exports[`General use should error if the variables do not deep equal 1`] = `
Expand All @@ -24,7 +26,12 @@ exports[`General use should error if the variables do not deep equal 1`] = `
__typename
}
}
, variables: {"username":"some_user","age":42}]

Expected variables: {"username":"some_user","age":42}

Failed to match 1 mock for this query, which had the following variables:
{"age":13,"username":"some_user"}
]
`;

exports[`General use should error if the variables in the mock and component do not match 1`] = `
Expand All @@ -34,7 +41,12 @@ exports[`General use should error if the variables in the mock and component do
__typename
}
}
, variables: {"username":"other_user"}]

Expected variables: {"username":"other_user","age":<undefined>}

Failed to match 1 mock for this query, which had the following variables:
{"username":"mock_username"}
Comment on lines +45 to +48
Copy link
Member

@benjamn benjamn Jun 7, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With my changes, undefined values now print as <undefined> rather than "undefined". This makes sense because these values are not actually strings, and while the <undefined> syntax is not legal JSON, that's fine because these strings are just for display (not for JSON.parse to consume later).

]
`;

exports[`General use should mock the data 1`] = `
Expand Down Expand Up @@ -64,7 +76,9 @@ exports[`General use should return "No more mocked responses" errors in response
__typename
}
}
, variables: {}]

Expected variables: {}
]
`;

exports[`General use should support custom error handling using setOnError 1`] = `
Expand All @@ -74,5 +88,7 @@ exports[`General use should support custom error handling using setOnError 1`] =
__typename
}
}
, variables: {"username":"mock_username"}]

Expected variables: {"username":"mock_username"}
]
`;
53 changes: 34 additions & 19 deletions src/utilities/testing/mocking/mockLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,18 @@ import {
removeClientSetsFromDocument,
removeConnectionDirectiveFromDocument,
cloneDeep,
makeUniqueId,
} from '../../../utilities';

export type ResultFunction<T> = () => T;

function stringifyForDisplay(value: any): string {
const undefId = makeUniqueId("stringifyForDisplay");
return JSON.stringify(value, (key, value) => {
return value === void 0 ? undefId : value;
}).split(JSON.stringify(undefId)).join("<undefined>");
}

export interface MockedResponse<TData = Record<string, any>> {
request: GraphQLRequest;
result?: FetchResult<TData> | ResultFunction<FetchResult<TData>>;
Expand Down Expand Up @@ -72,34 +80,41 @@ export class MockLink extends ApolloLink {
public request(operation: Operation): Observable<FetchResult> | null {
this.operation = operation;
const key = requestToKey(operation, this.addTypename);
let responseIndex: number = 0;
const response = (this.mockedResponsesByKey[key] || []).find(
(res, index) => {
const requestVariables = operation.variables || {};
const mockedResponseVariables = res.request.variables || {};
if (equal(requestVariables, mockedResponseVariables)) {
responseIndex = index;
return true;
}
return false;
const unmatchedVars: Array<Record<string, any>> = [];
const requestVariables = operation.variables || {};
const mockedResponses = this.mockedResponsesByKey[key];
const responseIndex = mockedResponses ? mockedResponses.findIndex((res, index) => {
const mockedResponseVars = res.request.variables || {};
if (equal(requestVariables, mockedResponseVars)) {
return true;
}
);
unmatchedVars.push(mockedResponseVars);
return false;
}) : -1;

const response = responseIndex >= 0
? mockedResponses[responseIndex]
: void 0;

let configError: Error;

if (!response || typeof responseIndex === 'undefined') {
if (!response) {
configError = new Error(
`No more mocked responses for the query: ${print(
operation.query
)}, variables: ${JSON.stringify(operation.variables)}`
);
`No more mocked responses for the query: ${print(operation.query)}
Expected variables: ${stringifyForDisplay(operation.variables)}
${unmatchedVars.length > 0 ? `
Failed to match ${unmatchedVars.length} mock${
unmatchedVars.length === 1 ? "" : "s"
} for this query, which had the following variables:
${unmatchedVars.map(d => ` ${stringifyForDisplay(d)}`).join('\n')}
` : ""}`);
} else {
this.mockedResponsesByKey[key].splice(responseIndex, 1);
mockedResponses.splice(responseIndex, 1);

const { newData } = response;
if (newData) {
response.result = newData();
this.mockedResponsesByKey[key].push(response);
mockedResponses.push(response);
}

if (!response.result && !response.error) {
Expand Down Expand Up @@ -151,7 +166,7 @@ export class MockLink extends ApolloLink {
): MockedResponse {
const newMockedResponse = cloneDeep(mockedResponse);
const queryWithoutConnection = removeConnectionDirectiveFromDocument(
newMockedResponse.request.query
newMockedResponse.request.query
);
invariant(queryWithoutConnection, "query is required");
newMockedResponse.request.query = queryWithoutConnection!;
Expand Down