I believe you have heard about Playwright and its a great support for browser automation tests. A week ago Playwright released support for API testing and I hope you are excited about it as I am.
REST API of course! Can I use Playwright for testing GraphQL endpoint? YES !
Keep reading to find out how easy it is.
Now you can start a new Playwright project with just one command:
1npm init playwright api-tests
1npm install faker
In the e2e folder, you can find example.spec.js - I won't be using it so please bin it and create file api.spec.js. In playwright.config.js please remove the projects array (one that lists browsers and devices) - we won't need it. In the use section please add baseURL :
(I am using my GraphQL endpoint https://graphql-teas-endpoint.netlify.app/ with methods to get all teas, get one tea, add a new tea or delete a tea)
In playwright.config.js you can also pass httpHeaders ( Content type , authorization etc) and httpCredentials .
To execute tests run
1npx playwright test
to run with reporter
1npx playwright test --reporter=html
We will be using Playwright test runner so import it on the top of the file along with faker.
On the top, I also define a few variables and queries:
If you have used Playwright test runner before you will be familiar how the scope of the test looks like, the difference is that instead of using page object we will be using request
A little bit about the above test:
There are a few methods available on response object:
To understand what they represent best lets log it in the console:
Going back to GraphQL tests as with other API testing tools with Playwright the most difficult part is to figure out query string. Please refer to your GraphQL endpoint Playground to build the right one.
Get one tea:
Add a new tea call:
And grab a new tea id assign it to a variable and use it to delete the object later.
Once you have JSON response back there is no limit with assertions: check the length, check data type, assert that contains particular string etc.
I highly encourage you to use this endpoint for testing and exploring what other methods are available there ( get all tea producers or add a new one ). The source code for my tests is available here
Playwright documentation regarding API testing: https://playwright.dev/docs/test-api-testing
You can also join their Slack channel and ask questions if you are blocked with anything.
There are other posts on my blog about GraphQL Testing tools, browse them here