Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/batrdn/nock-graphql
Minimal client-side GraphQL testing tool
https://github.com/batrdn/nock-graphql
graphql graphql-mock graphql-testing nock nock-graphql unit-testing
Last synced: 28 days ago
JSON representation
Minimal client-side GraphQL testing tool
- Host: GitHub
- URL: https://github.com/batrdn/nock-graphql
- Owner: batrdn
- License: mit
- Created: 2021-04-12T03:23:32.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2024-03-03T14:51:51.000Z (10 months ago)
- Last Synced: 2024-12-01T13:12:39.158Z (about 1 month ago)
- Topics: graphql, graphql-mock, graphql-testing, nock, nock-graphql, unit-testing
- Language: TypeScript
- Homepage:
- Size: 280 KB
- Stars: 18
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# nock-graphql
A nock-based GraphQL testing library that provides a functionality to mock queries and mutations.
In contrast to Apollo's MockedProvider, nock allows a realistic testing with the actual `http` calls being made from your client code.## Installing
You'll need `nock`, `cross-fetch` as peer dependencies in order to use this library.
```
npm install -D nock-graphql nock cross-fetch
```Additionally, you need to set up global `fetch` implementation incorporated in your `jest` environment:
```
global.fetch = require('cross-fetch')
```or, directly in your `ApolloClient`
```react
const client = new ApolloClient({
link: new HttpLink({ fetch, uri: ENDPOINT }),
});
```## Usage
I. Create `nock-graphql` instance
A. You could create it globally:
```typescript
// Create the instance in a separate file and export it.
import { NockGraphQL } from 'nock-graphql';export const nockgql = new NockGraphQL('http://localhost:4000/graphql');
```B. Create directly in the test files:
```typescript
import { NockGraphQL } from 'nock-graphql';let nockgql: NockGraphQL;
beforeAll(() => {
nockgql = new NockGraphQL('http://localhost:4000/graphql');
});
```II. Mocking queries
```typescript
import { gql } from 'graphql-tag';
import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client';
import { MockConfig } from 'nock-graphql';type QueryVariables = {
id: string;
};type QueryResult = {
foo: { bar: string };
};const GetQuery = gql`
query Test($id: String) {
foo(id: $id) {
bar
}
}
`;beforeEach(() => {
client = new ApolloClient({
link: new HttpLink({ uri: 'http://localhost:4000/graphql' }),
cache: new InMemoryCache({ addTypename: false }),
});
});afterEach(() => {
nockgql.cleanup();
});test('should match the query', async () => {
const config: MockConfig = {
document: GetQuery,
variables: { id: '1' },
data: {
foo: {
bar: 'Hello, World',
},
},
};const scope = nockgql.mock(config);
await client.query({ query: GetQuery, variables: { id: '1' } });scope.done();
});
```