GraphQL 是一种用于 API 的查询语言,而 Apollo Client 是一个强大的状态管理库,可以帮助你管理本地和远程数据。在开发过程中,模拟 API 调用可以让你在不依赖真实后端的情况下进行前端开发。
import { ApolloClient, InMemoryCache } from '@apollo/client';
import { MockLink } from '@apollo/client/testing';
const mockLink = new MockLink([
{
request: {
query: YOUR_QUERY,
variables: { id: '1' },
},
result: {
data: {
user: {
id: '1',
name: 'Mock User',
email: 'mock@example.com',
},
},
},
},
]);
const client = new ApolloClient({
link: mockLink,
cache: new InMemoryCache(),
});
import { ApolloClient, InMemoryCache } from '@apollo/client';
import { SchemaLink } from '@apollo/client/link/schema';
import { makeExecutableSchema } from '@graphql-tools/schema';
const typeDefs = `
type User {
id: ID!
name: String!
email: String!
}
type Query {
user(id: ID!): User
}
`;
const resolvers = {
Query: {
user: (_, { id }) => ({
id,
name: 'Mock User',
email: 'mock@example.com',
}),
},
};
const schema = makeExecutableSchema({ typeDefs, resolvers });
const client = new ApolloClient({
link: new SchemaLink({ schema }),
cache: new InMemoryCache(),
});
import { setupWorker, graphql } from 'msw';
const worker = setupWorker(
graphql.query('GetUser', (req, res, ctx) => {
return res(
ctx.data({
user: {
id: req.variables.id,
name: 'Mock User',
email: 'mock@example.com',
},
})
);
})
);
// 在应用启动前调用
worker.start();
原因:模拟数据没有严格遵循schema定义 解决:使用graphql-tools的schema验证功能确保模拟数据符合类型定义
原因:MockLink只处理了查询 解决:为mutation添加相应的mock处理
new MockLink([
{
request: {
query: UPDATE_USER,
variables: { id: '1', name: 'New Name' },
},
result: {
data: {
updateUser: {
id: '1',
name: 'New Name',
},
},
},
},
]);
解决:可以添加延迟来模拟网络延迟
new MockLink([
{
request: { query: YOUR_QUERY },
result: { data: { ... } },
delay: 300, // 300ms延迟
},
]);
interface User {
id: string;
name: string;
email: string;
}
const createMockUser = (overrides?: Partial<User>): User => ({
id: '1',
name: 'Mock User',
email: 'mock@example.com',
...overrides,
});
通过以上方法,你可以在React-Apollo应用中有效地模拟GraphQL API调用,提高开发效率和测试可靠性。
没有搜到相关的文章