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

fix: strengthen MockedResponse.newData type (#11584) #11592

Merged
merged 6 commits into from
Feb 15, 2024
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
5 changes: 5 additions & 0 deletions .changeset/dirty-insects-return.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@apollo/client": patch
---

Strengthen `MockedResponse.newData` type
55 changes: 54 additions & 1 deletion src/testing/core/mocking/__tests__/mockLink.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,60 @@
import gql from "graphql-tag";
import { MockLink } from "../mockLink";
import { MockLink, MockedResponse } from "../mockLink";
import { execute } from "../../../../link/core/execute";

describe("MockedResponse.newData", () => {
const setup = () => {
const weaklyTypedMockResponse: MockedResponse = {
request: {
query: gql`query A { a }`,
},
};

const stronglyTypedMockResponse: MockedResponse<{ a: string }, { input: string }> = {
request: {
query: gql`query A { a }`,
}
};

return {
weaklyTypedMockResponse,
stronglyTypedMockResponse,
};
}

test("returned 'data' can be any object with untyped response", () => {
const { weaklyTypedMockResponse } = setup();

weaklyTypedMockResponse.newData = ({ fake: { faker } }) => ({
data: {
pretend: faker,
},
});
});

test("can't return output that doesn't match TData", () => {
const { stronglyTypedMockResponse } = setup();

// @ts-expect-error return type does not match `TData`
stronglyTypedMockResponse.newData = () => ({
data: {
a: 123
}
});
});

test("can't use input variables that don't exist in TVariables", () => {
const { stronglyTypedMockResponse } = setup();

// @ts-expect-error unknown variables
stronglyTypedMockResponse.newData = ({ fake: { faker } }) => ({
data: {
a: faker
}
});
});
});

/*
We've chosen this value as the MAXIMUM_DELAY since values that don't fit into a 32-bit signed int cause setTimeout to fire immediately
*/
Expand Down
2 changes: 1 addition & 1 deletion src/testing/core/mocking/mockLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export interface MockedResponse<
error?: Error;
delay?: number;
variableMatcher?: VariableMatcher<TVariables>;
newData?: ResultFunction<FetchResult>;
newData?: ResultFunction<FetchResult<TData>, TVariables>;
}

export interface MockLinkOptions {
Expand Down
Loading