溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Jest如何測試GraphQL API

發(fā)布時間:2024-08-27 19:53:39 來源:億速云 閱讀:79 作者:小樊 欄目:編程語言

要使用Jest測試GraphQL API,你需要遵循以下步驟:

  1. 安裝必要的依賴項:

確保你已經(jīng)安裝了jest、graphqlapollo-server-testing。如果沒有,請使用以下命令安裝:

npm install --save-dev jest graphql apollo-server-testing
  1. 創(chuàng)建一個測試文件:

在你的項目中創(chuàng)建一個新的測試文件,例如graphql.test.js。這將包含你的GraphQL API測試。

  1. 設(shè)置Apollo Server:

首先,你需要設(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 });
  1. 編寫測試:

現(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!');
  });
});
  1. 運(yùn)行測試:

最后,運(yùn)行你的Jest測試:

npx jest

這將執(zhí)行你的GraphQL API測試,并顯示結(jié)果。你可以根據(jù)需要添加更多的測試用例來覆蓋你的API。

向AI問一下細(xì)節(jié)

免責(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)容。

AI