![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
graphql-automock
Advanced tools
Automatically mock GraphQL schemas for better testing.
Features:
react-apollo
for simple UI testingInstall via npm or yarn:
npm install --save-dev graphql-automock
yarn add --dev graphql-automock
Simply pass your GraphQL type definitions to mockSchema
and
you're ready to go:
import { mockSchema } from "graphql-automock";
import { graphql } from "graphql";
const types = `
type Query {
recentPosts: [Post!]!
}
type Post {
id: ID!
content: String!
likes: Int!
}
`;
const mocked = mockSchema(types);
const query = `{
recentPosts {
id
content
likes
}
}`;
graphql(mocked, query);
Without any further configuration, this query will return:
{
"data": {
"recentPosts": [
{
"id": "recentPosts.0.id",
"content": "recentPosts.0.content",
"likes": 2
},
{
"id": "recentPosts.1.id",
"content": "recentPosts.1.content",
"likes": 2
}
]
}
}
To understand how these values are derived, see Default values.
In addition to schema mocking, <MockApolloProvider>
makes the testing of your UI components much easier.
Wrapping components in a <MockApolloProvider>
allows any graphql()
and <Query>
components in the tree to receive mock data.
However note that components will first enter a loading state before the query resolves and components re-render.
<MockApolloProvider>
, together with a controller
, allows you to step through GraphQL execution to test both loading and ready states.
import { MockApolloProvider, controller } from "graphql-automock";
import TestUtils from "react-dom/test-utils";
it("renders a Post", async () => {
const tree = TestUtils.renderIntoDocument(
<MockApolloProvider schema={types}>
<Post id="123" />
</MockApolloProvider>
);
// Execution is automatically paused, allowing you to test loading state
const spinners = TestUtils.scryRenderedComponentsWithType(tree, Spinner);
expect(spinners).toHaveLength(1);
// Allow schema to run, and wait for it to finish
await controller.run();
// Test success state
const content = TestUtils.scryRenderedComponentsWithType(tree, Content);
expect(content).toHaveLength(1);
});
Automatically mocking the entire schema with sensible, deterministic data allows test code to customize only the data that affects the test. This results in test code that is more concise and easier to understand:
// We're only interested in the behaviour of likes...
it("hides the likes count when there are no likes", () => {
const mocks = {
Post: () => ({
likes: 0 // ...so we only customize that data
})
};
// Using mockSchema
const mockedSchema = mockSchema({
schema: types,
mocks: mocks
});
// Using MockApolloProvider
const mockedElements = (
<MockApolloProvider schema={types} mocks={mocks}>
<Post id="123" />
</MockApolloProvider>
);
// Continue with test...
});
Both GraphQL errors and network errors can be mocked.
Just like with a real GraphQL implementation, GraphQL errors are generated by throwing an error from a (mock) resolver.
import { mockSchema } from "graphql-automock";
mockSchema({
schema: types,
mocks: {
Post: () => {
throw new Error("Could not retrieve Post");
}
}
});
Since network errors are external to the GraphQL schema, they are simulated through the controller
.
import { MockApolloProvider, controller } from "graphql-automock";
import TestUtils from "react-dom/test-utils";
it("renders a Post", async () => {
const tree = TestUtils.renderIntoDocument(
<MockApolloProvider schema={types}>
<Post id="123" />
</MockApolloProvider>
);
// Test loading state
const spinners = TestUtils.scryRenderedComponentsWithType(tree, Spinner);
expect(spinners).toHaveLength(1);
// Simulate a network error
await controller.run({
networkError: () => new Error("Disconnected")
});
// Test error state
const errorMessage = TestUtils.scryRenderedComponentsWithType(
tree,
ErrorMessage
);
expect(errorMessage).toHaveLength(1);
});
To ensure that tests are reliable, the values generated by graphql-automock are 100% deterministic. The following default values are used:
true
2
3.14
2
Create a mocked GraphQL schema.
function mockSchema(schema: String | GraphQLSchema): GraphQLSchema;
function mockSchema({
schema: String | GraphQLSchema,
mocks: { [String]: MockResolverFn }
}): GraphQLSchema;
Create a mocked Apollo Client.
function mockApolloClient(schema: String | GraphQLSchema): ApolloClient;
function mockApolloClient({
schema: String | GraphQLSchema,
mocks: { [String]: MockResolverFn },
controller: Controller
}): ApolloClient;
React component that renders a mocked ApolloProvider.
<MockApolloProvider
schema={String | GraphQLSchema}
mocks={{ [String]: MockResolverFn }}
controller={Controller}
>
type MockResolverFn = (parent, args, context, info) => any;
Gives precise control over GraphQL execution, as well as enabling network errors to be simulated.
function pause(): void;
Pause GraphQL execution until it is explicitly resumed.
Controller starts in this state.
function run(): Promise<void>;
function run({ networkError: () => any }): Promise<void>;
Resume GraphQL execution if it is paused.
Returns a Promise that resolves when all pending queries have finished executing. If execution was not paused, then it returns a resolved Promise.
If a networkError
function is provided, pending and subsequent queries will fail with the result of calling that function. The function is called once for each query.
FAQs
Automock GraphQL schemas for better testing
We found that graphql-automock demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.