Extends supertest to test a GraphQL endpoint
npm install supertest-graphql> Extends supertest to test a GraphQL endpoint
``sh`
npm install supertest-graphql
`ts
import request from 'supertest-graphql'
import gql from 'graphql-tag'
test('should get pets', async () => {
const { data } = await request(app)
.query(gql
query {
pets {
name
petType
}
}
)`
.expectNoErrors()
expect(data.pets).toHaveLength(2)
})
will verify that the API response has no errors in
its result payload.`ts
await request(app)
.query('blooop')
.expectNoErrors()
// expected no errors but got 1 error(s) in GraphQL response: Syntax Error: Unexpected Name "blooop".
`
$3
`ts
const { data } = await request(app)
.query(gql)
.variables({ first: 4 })
`$3
`ts
const { data } = await request(app)
.mutate(gql)
.variables({petId: 'my-cat' })
`$3
`ts
import { supertestWs } from 'supertest-graphql'
import gql from 'graphql-tag'// for websocket the server needs to be started and stopped manually
beForeEach(() => server.listen(0, "localhost"))
afterEach(() => server.close())
test('should get pets', async () => {
const sub = await supertestWs(app)
.subscribe(gql
)
// will wait or pop the next value
const { data } = await sub.next().expectNoErrors() expect(data.newPetAdded.name).toEqual('Fifi')
})
`$3
`ts
const { data } = await request(app)
.auth('username', 'password')
.query(...)
`or via headers:
`ts
const { data } = await request(app)
.set('authorization', 'my token')
.query(...)
`For WebSocket with
connectionParams:
`ts
import { supertestWs } from 'supertest-graphql'const sub = await supertestWs(app)
.connectionParams({
token: 'my token'
})
.subscribe(...)
`
$3
By default, the execution are sent to
/graphql.You can change this with
.path():`ts
const { data } = await request(app)
.path('/new-graphql')
.query(...)
`$3
`ts
import { supertestWs, LEGACY_WEBSOCKET_PROTOCOL } from 'supertest-graphql'const sub = await supertestWs(app)
.protocol(LEGACY_WEBSOCKET_PROTOCOL)
.subscribe(...)
``