benawad / apollo-mocked-provider Goto Github PK
View Code? Open in Web Editor NEWAutomatically mock GraphQL data with a mocked ApolloProvider
License: MIT License
Automatically mock GraphQL data with a mocked ApolloProvider
License: MIT License
I have the following in my app: doMutation().catch(e => doSomething(e.graphQLErrors))
.
doSomething()
is called.ApolloMockedProvider
custom resolver, doSomething()
is not called.Repro: https://github.com/lorensr/apollo-mocked-provider/tree/repro-no-throw
The below console.log
is not called when running npm test -- -t "mock Mutation"
Note that if you add a
.then(response)
, the error is contained inresponse.errors
.
Getting the Could not find "client" in the context or passed in as an option. Wrap the root component in an <ApolloProvider>, or pass an ApolloClient instance in via options.
error after upgrading 3.3.7 - though I am not sure that specific version is the cause. It was working completely fine on ^3.2.0
As the title says, how can I mock a type such as DateTime
? π
const MockedNavBarSubscriber = ({ mockResponse, ...props }) => (
<ApolloMockedProvider
customResolvers={{
DateTime: () => new Date(),
Query: () => ({ me: () => mockResponse.me, company: () => mockResponse.company })
}}
>
<NavBarSubscriber {...props} />
</ApolloMockedProvider>
);
Hello,
It is not in the documentation but I would like to know if using query aliases are supported by the library.
I have a graphql query like this:
query Gifts {
gifts {
freeGifts: generateGift(price: 0) {
edges {
id,
name
}
}
saleGifts: generateGift(price: 9) {
edges {
id,
name
}
}
}
This is the mock I supply to my custom resolver:
const giftsMock = {
Gifts: () => ({
freeGifts: {
edges: [],
},
saleGifts: {
edges: [],
},
}),
};
For some reason, I am getting undefined for the freeGifts and saleGifts. I suspect this is because these are aliases. Can you confirm if aliases are support. Thank you in advance.
While trying out the lib, I noticed that my customResolvers were not working as I always receive default mocked data.
I'm not sure but it could be because you're missing the preserveResolvers: false
param in the addMockFunctionsToSchema.
I'm not sure if I am doing something wrong ? Do I need to pass a variable to the my customResolver query ? And if so, how do I do that ?
Here is the component I'm trying to test:
// @flow
import React from "react";
import { Query } from "react-apollo";
import ContactsList from "./ContactsList/ContactsList";
type Props = {
accountId: string
};
const GET_ACCOUNT_CONTACTS = gql`
query account($accountId: ID!) {
account(id: $accountId) {
id
contacts {
id
firstName
lastName
email
phoneNumber
profession
}
}
}
`;
export const ContactsQuery = ({ accountId }: Props) => (
<Query query={GET_ACCOUNT_CONTACTS} variables={{ accountId }}>
{({ loading, error, data }) => {
if (loading || !data) return "Loading...";
if (error) return <h2>Error! {error.message}</h2>;
return (
<ContactsList accountId={accountId} contacts={data.account.contacts} />
);
}}
</Query>
);
Here is the test:
it("should render the contacts", async () => {
const customResolvers = {
Query: () => ({
account: () => ({
id: "5bb5ecb2c4641b506f50df3a",
contacts: [
{
id: "ertyuioizej",
firstName: "Firstname",
lastName: "Lastname",
email: "[email protected]",
phoneNumber: "0488338833",
profession: "developer"
},
{
id: "tesitnguheuheuh",
firstName: "Firstname 2",
lastName: "Lastname 2",
email: "[email protected]",
phoneNumber: "0499338833",
profession: "tester"
}
]
})
})
};
const { container, debug, getAllByText } = render(
<ApolloMockedProvider customResolvers={customResolvers}>
<ContactsQuery accountId={"5bb5ecb2c4641b506f50df3a"} />
</ApolloMockedProvider>
);
debug();
await Promise.resolve();
debug();
All of our graphql queries are wrapped in the same object name, so if a component is running multiple queries I don't know of a way to pass each individual resolver to that corresponding query.
Here is an example query, and all of our queries are done this way. It's grabbing account information for our claimant, then returning the data in an object like this:
query GET_CLAIMS_ALERTS($account_number: ID!) {
account(id: $account_number) {
items {
claims {
items {
alerts {
publicID
alertDescription
isRead
}
}
}
}
}
}
However, in multiple sections I'll be grabbing claim information as well as incidents or alerts, and I don't know a way to send multiple resolvers that signify each query when all go into the account
object. I kinda like this repository, but as I was implementing this I noticed this issue along the way, and don't know I should do.
Hello,
I'm trying to figure out how to change the path where typeDefs.js is generated. Is there an option within the fetchTypeDefs object?
Rather than downloading it to the root of my project, could I set it to be generated somewhere else?
As of this morning, the npm build appears to be missing the dist folder. This means the package cannot be used.
I have this problem my resolver doesn't return the data in the second call for the same Query.
I'd like to have my type def file live inside my src directory. If there was a path option, I could make it happen using the tool.
When managing local state with the @client
directive as described in the Apollo docs, the mocking fails because the client resolvers are not available to theApolloClient
created here:
apollo-mocked-provider/src/createApolloMockedProvider.tsx
Lines 41 to 51 in 29a9d46
I think local state can be supported by adding a clientResolvers
option to ApolloMockedProviderOptions
and passing that (as resolvers
) to the ApolloClient
when it's created.
Let me know if this is already supported and I am just missing something.
If you think this would be good change, I can make a PR.
Hi @benawad - thanks a bunch for this library! It's been really helpful in simplifying my app's tests.
I would really appreciate a changelog between v2 and v3 - the commit history is a little hard to read and it would be nice to know what the breaking changes are (if you are following semver), or what the changes are in general. Thanks!
IME, tools like https://github.com/conventional-changelog/standard-version are great if you are willing to stick to a commit style... but that's totally up to you! :)
I didn't find a way to achieve this so here is my idea:
It would be nice to have the possibility to pass different custom resolvers for the same query inside a test. Refetching a query after a mutation is resolved and testing if the UI updated with the second resolvers data would be useful.
Is possible to pass a custom resolver with no data to the ApolloMockedProvider to simulate a scenario where the query returns an empty array?
My test that was working when using the registry version of [email protected]
now fails after npm link
in a local copy of this repo (both on latest master and b4e22ef) and npm link apollo-mocked-provider
in my app.
console.error node_modules/react-dom/cjs/react-dom.development.js:19527
The above error occurred in the <_default> component:
in _default (at TableOfContents.test.js:8)
in ApolloProvider
in Unknown (at setupTests.js:37)
in Router (at setupTests.js:26)
in RouterWrapper (at setupTests.js:36)
in MockedWrapper
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://fb.me/react-error-boundaries to learn more about error boundaries.
β TableOfContents βΊ should render loading and chapters
Invariant Violation: Could not find "client" in the context or passed in as an option. Wrap the root component in an <ApolloProvider>, or
pass an ApolloClient instance in via options.
36 |
37 | export default () => {
> 38 | const { data: { chapters } = {}, loading } = useQuery(CHAPTER_QUERY)
| ^
39 | const client = useApolloClient()
40 |
41 | return (
at new InvariantError (node_modules/@apollo/client/node_modules/ts-invariant/lib/invariant.esm.js:12:28)
at Object.invariant (node_modules/@apollo/client/node_modules/ts-invariant/lib/invariant.esm.js:24:15)
at QueryData.Object.<anonymous>.OperationData.refreshClient (node_modules/@apollo/client/react/data/OperationData.js:29:75)
at QueryData.Object.<anonymous>.QueryData.execute (node_modules/@apollo/client/react/data/QueryData.js:87:14)
at node_modules/@apollo/client/react/hooks/utils/useBaseQuery.js:35:95
at useDeepMemo (node_modules/@apollo/client/react/hooks/utils/useDeepMemo.js:6:42)
at useBaseQuery (node_modules/@apollo/client/react/hooks/utils/useBaseQuery.js:35:18)
at useQuery (node_modules/@apollo/client/react/hooks/useQuery.js:3:12)
at _default (src/components/TableOfContents.js:38:48)
at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:14803:18)
at mountIndeterminateComponent (node_modules/react-dom/cjs/react-dom.development.js:17482:13)
at beginWork (node_modules/react-dom/cjs/react-dom.development.js:18596:16)
at HTMLUnknownElement.callCallback (node_modules/react-dom/cjs/react-dom.development.js:188:14)
at Object.invokeGuardedCallbackDev (node_modules/react-dom/cjs/react-dom.development.js:237:16)
at invokeGuardedCallback (node_modules/react-dom/cjs/react-dom.development.js:292:31)
at beginWork$1 (node_modules/react-dom/cjs/react-dom.development.js:23203:7)
at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:22157:12)
at workLoopSync (node_modules/react-dom/cjs/react-dom.development.js:22130:22)
at performSyncWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:21756:9)
at scheduleUpdateOnFiber (node_modules/react-dom/cjs/react-dom.development.js:21188:7)
at updateContainer (node_modules/react-dom/cjs/react-dom.development.js:24373:3)
at node_modules/react-dom/cjs/react-dom.development.js:24758:7
at unbatchedUpdates (node_modules/react-dom/cjs/react-dom.development.js:21903:12)
at legacyRenderSubtreeIntoContainer (node_modules/react-dom/cjs/react-dom.development.js:24757:5)
at Object.render (node_modules/react-dom/cjs/react-dom.development.js:24840:10)
at node_modules/@testing-library/react/dist/pure.js:99:25
at batchedUpdates$1 (node_modules/react-dom/cjs/react-dom.development.js:21856:12)
at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:929:14)
at render (node_modules/@testing-library/react/dist/pure.js:95:26)
at mockedRender (src/setupTests.js:51:10)
at Object.it (src/components/TableOfContents.test.js:8:5)
Test Suites: 1 failed, 1 skipped, 1 of 2 total
I noticed that mock data is being stored in the cache and being re-used across tests. afterEach(cleanup);
doesn't appear to be working here:
/**
* @prettier
*/
/* eslint-disable filenames/match-regex */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import * as React from 'react';
import { cleanup } from '@testing-library/react';
import constant from 'lodash/constant';
import { ApolloMockedProvider } from '~/test/utils/apollo';
import render from '~/test/utils/render';
import AuthAccount from '.';
afterEach(cleanup);
describe('components/AuthAccount', () => {
test('renders children when user exists', async () => {
const { getByText } = render(
<ApolloMockedProvider
customResolvers={{
Query: () => ({
me: () => ({
_id: 'myId123',
}),
}),
}}
>
<AuthAccount>
<div>This should render</div>
</AuthAccount>
</ApolloMockedProvider>,
);
await Promise.resolve();
getByText('This should render');
});
test('does not render children when user does not exist', async () => {
const { debug, getByText } = render(
<ApolloMockedProvider
customResolvers={{
Query: () => ({
me: constant(null),
}),
}}
>
<AuthAccount>
<div>This should not render</div>
</AuthAccount>
</ApolloMockedProvider>,
);
await Promise.resolve();
getByText('This should not render'); // it still renders with id `myId123` :(
debug();
});
});
master
branch failed. π¨I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.
You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. Iβm sure you can resolve this πͺ.
Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.
Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master
branch. You can also manually restart the failed CI job that runs semantic-release.
If you are not sure how to resolve this, here is some links that can help you:
If those donβt help, or if this issue is reporting something you think isnβt right, you can always ask the humans behind semantic-release.
An npm token must be created and set in the NPM_TOKEN
environment variable on your CI environment.
Please make sure to create an npm token and to set it in the NPM_TOKEN
environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/
.
Good luck with your project β¨
Your semantic-release bot π¦π
Original post suggests a globalMocks option for passing base resolver mocks used across multiple tests (non-working gist here)
This presumes "merge resolvers" functionality to be done. Guess that we are waiting for this PR from graphql-tools repo, right?
The current createApolloErrorProvider
approach has a separate "throw an error for all requests". This is useful for inspecting the behavior of errors on initial load, but breaks down for me when I have a view that may render some data with a query (like a list of items) and execute another query/mutation on that data.
I'd prefer to be able to control the error handling within my custom resolvers. I've taken a crack at it here. Here is a snippet of usage:
<MockedProvider
customResolvers={{
Query: () => ({
todo: (_obj: any, args: any) => {
console.log(args.id)
throw new Error('Boom');
},
todos: () => [
{
text: 'Success',
},
],
}),
}}
>
This would allow a todos
query to execute, and then throw an error when todo(id: ID)
is executed. Optionally, a resolver can inspect its arguments and conditionally throw an error. This would allow for a more natural way of handling complex error scenarios.
It's not currently in createApolloLoadingProvider
or createApolloLoadingProvider
. In particular, I'd like to test my components with the latter while including my app's onError
link.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.