您好,登錄后才能下訂單哦!
要使用Jest測試GraphQL的實時查詢,你需要模擬WebSocket連接并在測試中發送和接收消息
npm install --save-dev jest @types/jest graphql-ws ws
創建一個__tests__
文件夾來存放你的測試文件。
在__tests__
文件夾中創建一個名為graphql-realtime.test.ts
的文件,然后編寫以下代碼:
import { createServer } from 'http';
import { Server } from 'ws';
import { GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql';
import { useServer } from 'graphql-ws/lib/use/ws';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import { execute, subscribe } from 'graphql';
import { PubSub } from 'graphql-subscriptions';
// 創建一個簡單的GraphQL schema
const schema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
message: {
type: GraphQLString,
resolve: () => 'Hello World!',
},
},
}),
subscription: new GraphQLObjectType({
name: 'Subscription',
fields: {
message: {
type: GraphQLString,
subscribe: (_, __, { pubsub }) => pubsub.asyncIterator('MESSAGE'),
},
},
}),
});
describe('GraphQL Realtime Query', () => {
let httpServer;
let wsServer;
let pubsub;
beforeEach(() => {
httpServer = createServer();
wsServer = new Server({ server: httpServer });
pubsub = new PubSub();
useServer(
{
schema,
execute,
subscribe,
context: () => ({ pubsub }),
},
wsServer
);
httpServer.listen(4000);
});
afterEach(() => {
if (httpServer) {
httpServer.close();
}
if (wsServer) {
wsServer.close();
}
});
it('should receive realtime messages', async () => {
// 創建一個WebSocket客戶端
const client = new WebSocket('ws://localhost:4000/graphql');
// 等待WebSocket連接建立
await new Promise((resolve) => client.onopen = resolve);
// 訂閱實時消息
client.send(JSON.stringify({
type: 'start',
id: '1',
payload: {
query: `
subscription {
message
}
`,
},
}));
// 發送實時消息
pubsub.publish('MESSAGE', { message: 'Hello from realtime query!' });
// 等待實時消息到達
const response = await new Promise((resolve) => client.onmessage = resolve);
// 斷言收到的消息
expect(JSON.parse(response.data)).toEqual({
type: 'data',
id: '1',
payload: { data: { message: 'Hello from realtime query!' } },
});
});
});
這個測試將創建一個GraphQL服務器,使用graphql-ws
庫提供實時查詢支持,并通過WebSocket連接發送和接收實時消息。測試將訂閱實時消息,然后發布一條消息,最后檢查是否收到了正確的消息。
npx jest __tests__/graphql-realtime.test.ts
這個測試應該能夠成功通過,表明你已經成功地使用Jest測試了GraphQL的實時查詢。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。