Assuming all files below now you can:
import { runMockQuery } from './graphql-test';
const dataQuery = '{ myData { prop1, prop2 } }'; // This is example GQL query string
function renderData(data) {...} // This renders `dataQuery` response
it('featchData should render', async () => {
const { data } = await runMockQuery(dataQuery); // This is mocked GQL response for query
const result = renderData(data);
expect(result).toRenderData(...);
});
import { runMockQuery } from './graphql-test';
import { mockVal } from './graphql-mocks';
const dataQuery = '{ myData { prop1, prop2 } }'; // This is example GQL query string
function isDataHasProp2(data) { return !!data.myData.prop2 }
it('isDataHasProp2 should return `false` when prop2 does not exists', async () => {
provideMocks(mockVal({
Query: mockVal({ prop2: () => null })
}));
const { data } = await runMockQuery(dataQuery); // Response will now have both prop1 and prop2
// But prop2 will be set to `null` while prop1 will be mocked with some real value
const result = renderData(data);
expect(result).toBe(false);
});
Just execute file graphql-mock-server.ts
with node (ts-node):
$ ts-node graphql-mock-server.ts
Then you can access server at http://localhost:8008
, or provide custom PORT
env.
With query like this:
query MyQuery {
getMy { prop1, prop2 }
}
gql-gen
for apollo-angular
will generate injectable service named MyQueryGQL
.
It then can be used:
import { Component } from '@angular/core';
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { expectQueryAndFlushWithData } from './graphql-test-angular';
import { MyQueryGQL } from './generated/graphql';
@Component({
selector: 'my-component',
template: `<p *ngIf="my$ | async as my">prop1 is {{my.data.getMy.prop1}}, prop2 is {{my.data.getMy.prop2}}</p>`
})
class MyComponent {
my$ = this.myQueryGQL.watch();
constructor(public myQueryGQL: MyQueryGQL) {}
}
beforeEach(...); // Default setup of TesBed with MyComponent
it('MyComponent should render data from MyQueryGQL', fakeAsync(async () => {
const fixture = TestBed.createComponent(MyComponent);
// This will validate that query `MyQueryGQL` was called and also flush mocked data back to component
// You can get generated data as `mockData` from returned object
const { mockData } = await expectQueryAndFlushWithData(MyQueryGQL);
tick(); // This is required since graphql resolves data asynchronously
fixture.detectChanges(); // Then we render that data
// Then do your assertions here
expect(...).toRenderFrom(mockData); // Check if it rendered mock data from `mockData`
}));