-
Notifications
You must be signed in to change notification settings - Fork 2.7k
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
Breaking change from 3.0.2 to 3.1.0 [ MockedProvider ] #6803
Comments
+1 We're also experiencing this issue |
@tyagow as a work around, you can mock import * as Apollo from '@apollo/client';
jest.spyOn(Apollo, 'useQuery').mockImplementation(() => {
return {
loading: false,
error: undefined,
data: { MOCK_DATA },
refetch: jest.fn()
}
}); |
Thank you, great idea! const mergeResolvers = (target, input) => {
const inputTypenames = Object.keys(input);
const merged = inputTypenames.reduce(
(accum, key) => {
const inputResolver = input[key];
if (target[key]) {
const targetResolver = target[key];
const resolvedInput = inputResolver();
const resolvedTarget = targetResolver();
if (
!!resolvedTarget &&
!!resolvedInput &&
isDict(resolvedTarget) &&
isDict(resolvedInput)
) {
const newValue = { ...resolvedTarget, ...resolvedInput };
return {
...accum,
[key]: () => newValue,
};
}
}
return { ...accum, [key]: inputResolver };
},
{ ...target }
);
return merged;
};
const buildSchema = mocks => {
const schemaStr = print(schemaGQL) + clientDefs;
const schema = makeExecutableSchema({
typeDefs: schemaStr,
resolverValidationOptions: {
requireResolversForResolveType: false,
},
});
return addMocksToSchema({ schema, mocks, preserveResolvers: true });
};
export const ApolloProviderWithMock = ({ customResolvers, client, children }) => {
const mocks = mergeResolvers(globalMocks, customResolvers);
const schema = buildSchema(mocks);
let apolloClient = client;
if (!client) {
apolloClient = new ApolloClient({
fetch,
link: new SchemaLink({ schema }),
cache: new InMemoryCache({ possibleTypes }),
typeDefs: schema,
});
}
return <ApolloProvider client={apolloClient}>{children}</ApolloProvider>;
}; Then in a test I just need to wrap the component being tested with it. Also, I can set specific values for specific queries const customerResolver = {
Query: () => ({
SomeQuery: () => ({
[...]
})
})
}
<ApolloProviderWithMock customerResolver={customerResolver}>
<Component>
</ApolloProviderWithMock> |
I am actually unable to get import { render } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import { MockedProvider } from '@apollo/client/testing'
import { Route, MemoryRouter } from 'react-router-dom'
...
describe('pipeline: none', () => {
test('does not render environment section', async () => {
const { getByText } = render(
<MockedProvider
mocks={[
{
request: {
query: MARKETPLACE_OFFERING_QUERY,
variables: {
guid
}
},
result: {
data: {
offering: { guid, name: 'mock offering' }
}
}
}
]}
addTypename={false}
>
<MemoryRouter initialEntries={['builder/123/456']}>
<Route path="builder/:offering_guid/:plan_guid">
<Builder />
</Route>
</MemoryRouter>
</MockedProvider>
)
await new Promise(resolve => setTimeout(resolve, 0)) // wait for response
expect(getByText('mock offering')).toBeInTheDocument()
})
}) Leaving out this, the loading state is always true. With it the component is able to log out await new Promise(resolve => setTimeout(resolve, 0)) // wait for response The assertion fails, data is always undefined in the component even when |
My team seem to have run into the same problem :( |
Same here, the mock provider seems to stopped working in some cases while running the styleguidist server, and when generating the static version of the styleguidist, some cases do work. A bit unstable, and now we are currently deciding if we should revert, or look for a solution. |
In my case it was the same problem as described here: #6771 I added logging to my component that did the mutations and saw that the variables contained a field with an explicit e.g.
To:
|
In my case I added the prop like that, products {
name
description
price
__typename
} So I tried this and worked for me. However, the error still is a mystery for me. |
Get this error - |
I've resolved this with my post on this one
|
I found the issue to be the same as @Markus-ipse The change in behavior appears to have been introduced here, by switching to a different deep equal function: 2593f8f#diff-fab0a81f7f7c1e746fd7f86a7a1458c9 and 26849a8 The previous |
See benjamn/wryware#21 for explanation and motivation. Should help with #6771, #6803, #6688, #6378, and #7081, and possibly other regressions that began in @apollo/[email protected].
See benjamn/wryware#21 for explanation and motivation. Should help with #6771, #6803, #6688, #6378, and #7081, and possibly other regressions that began in @apollo/[email protected].
This behavior should be fixed/improved in |
Getting the same exampletest: describe("ProfileHeader", () => {
it.only("show a profile header", async () => {
const { container } = renderApollo(<ProfileHeader />, {
defaultOptions: {
query: { fetchPolicy: "no-cache" },
watchQuery: { fetchPolicy: "no-cache" },
},
});
await waitFor(() => {
expect(container).toMatchSnapshot();
});
}); renderApollo import { MockedProvider, MockedResponse } from "@apollo/client/testing";
const renderApollo = (
node: any,
{
mocks,
addTypename,
defaultOptions,
cache,
resolvers,
...options
}: RenderApolloOptions = {}
): RenderResult => {
return render(
<MockedProvider
mocks={mocks}
addTypename={addTypename}
defaultOptions={defaultOptions}
cache={cache}
resolvers={resolvers}
>
{node}
</MockedProvider>,
options
);
}; Component: const ProfileHeader: React.FC = () => {
const [queryExecutor, { loading, error, data }] = useLazyQuery<TMe>(
PROFILE_QUERY,
{
// fetchPolicy: "cache-only", // <!== If changing the fetchPolicy here, the test pass!
fetchPolicy: "cache-and-network",
nextFetchPolicy: "cache-first",
}
); It would seem like MockedProvider doesn't replace my useLazyQuery options with the defaultOptions passed from the test. EDIT: My issue is unrelated to this thread, sorry for the noise // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
jest.spyOn(Apollo, "useLazyQuery").mockImplementation(() => {
return [
jest.fn(),
{
data: null,
error: undefined,
loading: false,
},
];
}); |
Still experiencing this issue, even with setting fetchPolicy: no-cache, even with using the new beta version. The Dog example from the docs fails on my environment with direct copy/paste, "no more mocked responses". https://www.apollographql.com/docs/react/development-testing/testing/ worth noting that UPDATE: I was getting these errors because I had missed the necessity of cleanup between test runs. in create-react-app, I needed
FURTHER UPDATE: cleanup was not sufficient, the same specs were intermittently getting this error in CI even when passing locally. It was necessary to version bump to the beta. |
This fixes my issue @benjamn , do we have any visibility into a release schedule? This is blocking our development and it'd be great to have an estimate. Thanks! |
I was having this issue on any 3.x.x version (my mocks have correct variables + __typenames and all that junk, this seemed like a legitimate bug with MockedProvider), upgrading to @apollo/[email protected] did NOT fix it for me, but upgrading to @apollo/[email protected] DID fix it for me. edit: just wanted to say that this didn't fix everything, still had some tests that were failing that definitely should pass (spent hours checking typenames + variables, 100% sure things are accurate). We had the most trouble with components that had 2 different queries running in the same file as well as queries with empty variables), it always got confused.
basically just forcing no-cache for testing purposes |
The current apollo-client release is 3.3.5, and this seems to be fixed now. |
It doesn't sound like there is an outstanding issue here, so closing. Thanks! |
I'm still getting this on version |
@findlay-hannam Are you running multiple queries in a single test? Maybe you actually need to add more mocks. (But it's also possible there's still a bug somewhere.) |
I am running multiple queries, but the tests pass when I set the fetchPolicy to 'no-cache'. I'm currently using the workaround @btferus5 suggested |
Have similar issue with fetchPolicy |
Intended outcome:
Be able to mock a query using MockProvider
Actual outcome:
After updating to 3.1.0 tests broke with:
How to reproduce the issue:
Described in the first section but if more info is needed I can add here.
Versions
The text was updated successfully, but these errors were encountered: