Test Scripts
Test scripts run after the response is received. Use them to validate your API's behavior with assertions.
Writing a Test
rm.test('Test name', () => {
// assertions go here
})
If the function throws (or an rm.expect() fails), the test is marked as failed.
Common Assertions
Status code
rm.test('Status is 200', () => {
rm.expect(rm.response.code).to.equal(200)
})
rm.test('Status is success', () => {
rm.expect(rm.response.code).to.be.within(200, 299)
})
Response body
rm.test('Body has id field', () => {
const body = rm.response.json()
rm.expect(body).to.have.property('id')
})
rm.test('User name is Alice', () => {
rm.expect(rm.response.json().name).to.equal('Alice')
})
rm.test('Items is an array', () => {
rm.expect(rm.response.json().items).to.be.an('array')
})
Response time
rm.test('Response is fast', () => {
rm.expect(rm.response.responseTime).to.be.below(500) // ms
})
Headers
rm.test('Content-Type is JSON', () => {
rm.expect(rm.response.headers['content-type']).to.include('application/json')
})
Saving Response Values
Extract values from the response and store them as variables for use in later requests:
// Save token from login response
const token = rm.response.json().access_token
rm.environment.set('accessToken', token)
// Save created resource ID
const userId = rm.response.json().id
rm.environment.set('userId', userId.toString())
Assertion Reference
Rostyman uses Chai BDD assertions via rm.expect():
| Assertion | Example |
|---|---|
| Equal | rm.expect(val).to.equal(200) |
| Include | rm.expect(str).to.include('hello') |
| Have property | rm.expect(obj).to.have.property('id') |
| Be a type | rm.expect(val).to.be.a('string') |
| Be an array | rm.expect(val).to.be.an('array') |
| Be truthy | rm.expect(val).to.be.ok |
| Be null | rm.expect(val).to.be.null |
| Within range | rm.expect(val).to.be.within(1, 10) |
| Above / below | rm.expect(val).to.be.above(0) |
| Length | rm.expect(arr).to.have.lengthOf(3) |