剧透警告:以下内容与集成测试有关,不在 TypeScript 中,但我认为它可能有助于 OP 或其他希望彻底测试他们的数据源。
现在给出答案:
你可以从Apollo的优秀完整stack tutorial repo中获得灵感。这对我帮助很大。这是一个示例,您可以在其中看到他们模拟了来自 launchAPI 和 userAPI 数据源的响应。
it('books trips', async () => {
const {server, launchAPI, userAPI} = constructTestServer({
context: () => ({user: {id: 1, email: 'a@a.a'}}),
});
// mock the underlying fetches
launchAPI.get = jest.fn();
// look up the launches from the launch API
launchAPI.get
.mockReturnValueOnce([mockLaunchResponse])
.mockReturnValueOnce([{...mockLaunchResponse, flight_number: 2}]);
// book the trip in the store
userAPI.store = mockStore;
userAPI.store.trips.findOrCreate
.mockReturnValueOnce([{get: () => ({launchId: 1})}])
.mockReturnValueOnce([{get: () => ({launchId: 2})}]);
// check if user is booked
userAPI.store.trips.findAll.mockReturnValue([{}]);
const res = await server.executeOperation({
query: BOOK_TRIPS,
variables: {launchIds: ['1', '2']},
});
expect(res).toMatchSnapshot();
});
这是他们的constructTestServer 函数。
const constructTestServer = ({ context = defaultContext } = {}) => {
const userAPI = new UserAPI({ store });
const launchAPI = new LaunchAPI();
const server = new ApolloServer({
typeDefs,
resolvers,
dataSources: () => ({ userAPI, launchAPI }),
context,
});
return { server, userAPI, launchAPI };
};
module.exports.constructTestServer = constructTestServer;
这是一个更简单的示例,我在我称为 randomUserApi 的数据源上设置了一个普通的 get 请求。
it('randomUser > should return expected values', async () => {
const randomUserApi = new RandomUserApi();
const server = new ApolloServer({
schema,
dataSources: () => ({ randomUserApi }),
});
const mockResponse = {
results: [
{
email: 'jordi.ferrer@example.com',
},
],
info: {
seed: '54a56fbcbaf2d311',
},
};
randomUserApi.get = jest.fn();
randomUserApi.get.mockReturnValueOnce(mockResponse);
const query = `query Query {
randomUser {
results {
email
}
info {
seed
}
}
}`;
// run query against the server and snapshot the output
const response = await server.executeOperation({
query,
});
const { data, errors } = response;
expect(errors).toBeUndefined();
expect(data).toEqual({
randomUser: {
info: { seed: '54a56fbcbaf2d311' },
results: [{ email: 'jordi.ferrer@example.com' }],
},
});
});
这是RandomUserApi的代码:
const { RESTDataSource } = require('apollo-datasource-rest');
class RandomUserApi extends RESTDataSource {
constructor() {
// Always call super()
super();
// Sets the base URL for the REST API
this.baseURL = 'https://randomuser.me/';
}
async getUser() {
// Sends a GET request to the specified endpoint
return this.get('api/');
}
}
module.exports = RandomUserApi;
以及使用它的解析器
Query: {
randomUser: async (_parent, _args, context) => context.dataSources.randomUserApi.getUser(),
}
完全披露:发布相同的回复here