在GraphQL解析器中使用Sinon模拟数据库对象的方法如下:
npm install sinon --save-dev
const sinon = require('sinon');
const userDB = {
getUserById: sinon.stub().returns({ id: 1, name: 'John Doe' }),
createUser: sinon.stub().returns({ id: 2, name: 'Jane Smith' }),
// 其他数据库方法...
};
在上述代码中,使用Sinon的stub方法创建了getUserById和createUser两个数据库方法的模拟版本,并分别返回指定的用户对象。
const { graphql } = require('graphql');
const { makeExecutableSchema } = require('graphql-tools');
const typeDefs = `
type User {
id: ID!
name: String!
}
type Query {
getUserById(id: ID!): User
}
`;
const resolvers = {
Query: {
getUserById: (_, { id }) => userDB.getUserById(id), // 使用模拟数据库对象的方法
},
};
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
// 使用Sinon模拟数据库对象
const userDB = {
getUserById: sinon.stub().returns({ id: 1, name: 'John Doe' }),
createUser: sinon.stub().returns({ id: 2, name: 'Jane Smith' }),
// 其他数据库方法...
};
// 执行GraphQL查询
const query = `
query {
getUserById(id: 1) {
id
name
}
}
`;
graphql(schema, query).then(result => {
console.log(result);
});
在上述代码中,创建了一个包含getUserById方法的GraphQL查询,该方法直接使用了userDB模拟对象的getUserById方法。当执行这个GraphQL查询时,将得到模拟的用户对象。
请注意,上述示例仅展示了如何在GraphQL解析器中使用Sinon模拟数据库对象的一种方法,具体使用方式可能因项目而异。如果需要模拟其他数据库方法或者进行更复杂的模拟逻辑,可以参考Sinon的文档和示例进行操作。
腾讯云的相关产品和产品介绍链接地址见腾讯云官方网站,这里就不提及具体的品牌商了。
企业创新在线学堂
DBTalk
Techo Day
T-Day
企业创新在线学堂
云+社区技术沙龙[第17期]
Elastic 中国开发者大会
云+社区技术沙龙[第14期]
云原生正发声
云+社区技术沙龙第33期
企业创新在线学堂
领取专属 10元无门槛券
手把手带您无忧上云