要在Apollo GraphQL中模拟分段数据,可以使用MockLink
和InMemoryCache
。这样可以在应用程序开发的早期阶段模拟数据,并且可以与后端API解耦。
先安装所需的依赖:
npm install apollo-link apollo-link-http apollo-link-schema apollo-cache-inmemory graphql-tools graphql
然后创建一个mocked schema和数据源文件(例如mocks.js
):
const { ApolloServer, gql } = require('apollo-server');
const { makeExecutableSchema } = require('graphql-tools');
// 定义模拟数据
const books = [
{ id: '1', title: 'Book 1', author: 'Author 1' },
{ id: '2', title: 'Book 2', author: 'Author 2' },
{ id: '3', title: 'Book 3', author: 'Author 3' },
];
// 定义schema
const typeDefs = gql`
type Book {
id: ID!
title: String!
author: String!
}
type Query {
books(offset: Int!, limit: Int!): [Book!]!
}
`;
// 定义解析器
const resolvers = {
Query: {
books: (_, { offset, limit }) => books.slice(offset, offset + limit),
},
};
// 创建schema
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
// 创建ApolloServer
const server = new ApolloServer({ schema });
// 启动服务器
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`);
});
接下来,在应用程序中使用mocked schema和数据源。例如,如果使用React和Apollo Client:
import React from 'react';
import { ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client';
import { MockLink } from '@apollo/client/testing';
import { mocks } from './mocks';
// 创建mocked link
const link = new MockLink(mocks);
// 创建Apollo Client
const client = new ApolloClient({
cache: new InMemoryCache(),
link,
});
// 使用Apollo Provider包装根组件
const App = () => (
{/* 应用程序内容 */}
);
最后,在测试中使用mocked schema和数据源。例如,如果使用Jest进行测试:
import { ApolloClient, InMemoryCache } from '@apollo/client';
import { MockLink } from '@apollo/client/testing';
import { mocks } from './mocks';
// 创建mocked link
const link = new MockLink(mocks);
// 创建Apollo Client
const client = new ApolloClient({
cache: new InMemoryCache(),
link,
});
// 在测试中使用client进行查询
test('should return mocked books', () => {
const response = await client.query({
query: gql`
query GetBooks {
books(offset: 0, limit: 10) {
id
title
author
}
}
`,
});
// 检查返回的模拟数据
expect(response.data.books).toEqual([
{ id: '1', title: 'Book 1', author: 'Author 1' },
{ id: '2', title: 'Book 2', author: 'Author 2' },
{ id: '3', title: 'Book 3', author: 'Author 3' },
]);
});
这样,你就可以在Apollo GraphQL中模拟分段数据了。通过使用MockLink
和InMemoryCache
,你可以在应用程序开发的早期阶段模拟数据,并且可以与后端API解耦。