layout | lineNumbers | class |
---|---|---|
center |
true |
text-center |
An open-source library for testing RESTful APIs written in javascript for all levels in a Testing Pyramid.
npm install pactum <test-runner>
await spec().<command>().<command>()
a simple test case using PactumJS and mocha.
const { spec } = require('pactum');
it('should be a teapot', async () => {
await spec()
.get('http://httpbin.org/status/418')
.expectStatus(418);
});
const { spec } = require('pactum');
const { like } = require('pactum-matchers');
it('should create a new user', async () => {
await spec()
.post('https://reqres.in/api/users')
.withJson({
"name": "morpheus",
"job": "leader"
})
.expectStatus(201)
.expectJsonMatch('id', like("1"));
});
- templates
- maps
- functions
- stores
const { stash } = require('pactum');
stash.addDataTemplate({
'USER_DTO': {
"name": "morpheus",
"job": "leader"
}
});
await spec()
.post('https://reqres.in/api/users')
.withJson({
"@DATA:TEMPLATE@": "USER_DTO"
});
await spec()
.post('https://reqres.in/api/users')
.withJson({
'@DATA:TEMPLATE@': 'User',
'@OVERRIDES@': {
'job': 'member'
}
});
- spec
- expect
- interaction
const { handler } = require('pactum');
handler.addSpecHandler('get random users', (ctx) => {
const { spec, data } = ctx;
spec.get('https://randomuser.me/api');
spec.withQueryParams('results', data);
spec.expectStatus(200);
});
await spec('get random users', 2)
.expectJsonLike({
"results": "$V.length === 2"
});
await spec('get random users', 3)
.expectJsonLike({
"results": "$V.length === 3"
});
const { spec } = require('pactum');
it('should return all posts and first post should have comments', async () => {
await spec()
.get('http://jsonplaceholder.typicode.com/posts')
.expectStatus(200)
.stores('FirstPostId', '[0].id');
await spec()
.get(`http://jsonplaceholder.typicode.com/posts/{id}/comments`)
.withPathParams('id', '$S{FirstPostId}')
.expectStatus(200);
});
interactions will help to simulate the HTTP requests & responses
const { mock } = require('pactum');
mock.addInteraction({
request: {
method: 'GET',
path: '/api/hello'
},
response: {
status: 200,
body: 'Hello, 👋'
}
});
mock.start(3000);
graph LR;
subgraph Controlled Environment
t[Tests]
sut(Service Under Test)
ms(Mock Server)
db[(Database)]
t-- Request -->sut
sut-- Read/Write -->db
sut-- Request -->ms
ms-- Response -->sut
sut-- Response -->t
end
graph LR;
subgraph Workflow
u{{User}}
os(Order Service)
is(Inventory Server)
u-- Place Order -->os
os-- Check Inventory -->is
end
it('should buy a product which is in-stock', async () => {
await pactum.spec()
.useInteraction('get in-stock product from inventory-service')
.post('/api/order-service/v1/orders')
.withJson({
"product": "iPhone"
})
.expectStatus(200);
});
it('should not buy a product which is out-of-stock', async () => {
await pactum.spec()
.useInteraction('get out-of-stock product from inventory-service')
.post('/api/order-service/v1/orders')
.withJson({
"product": "iPhone"
})
.expectStatus(400);
});