您好,登錄后才能下訂單哦!
要使用Jest測試GraphQL API,你需要遵循以下步驟:
確保你已經(jīng)安裝了jest
、graphql
和apollo-server-testing
。如果沒有,請使用以下命令安裝:
npm install --save-dev jest graphql apollo-server-testing
在你的項目中創(chuàng)建一個新的測試文件,例如graphql.test.js
。這將包含你的GraphQL API測試。
首先,你需要設(shè)置一個Apollo Server實(shí)例,以便在測試中使用。這是一個簡單的示例,展示了如何創(chuàng)建一個基本的Apollo Server實(shí)例:
const { ApolloServer, gql } = require('apollo-server');
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => 'Hello, world!',
},
};
const server = new ApolloServer({ typeDefs, resolvers });
現(xiàn)在你可以開始編寫Jest測試。使用apollo-server-testing
庫中的createTestClient
函數(shù)創(chuàng)建一個測試客戶端,然后使用該客戶端發(fā)送GraphQL查詢。這是一個簡單的測試示例:
const { createTestClient } = require('apollo-server-testing');
const { server } = require('./your-apollo-server-file'); // 導(dǎo)入你的Apollo Server實(shí)例
const { query } = createTestClient(server);
describe('GraphQL API', () => {
it('should return "Hello, world!" from the "hello" query', async () => {
const response = await query({
query: `
query {
hello
}
`,
});
expect(response.data.hello).toBe('Hello, world!');
});
});
最后,運(yùn)行你的Jest測試:
npx jest
這將執(zhí)行你的GraphQL API測試,并顯示結(jié)果。你可以根據(jù)需要添加更多的測試用例來覆蓋你的API。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。