Skip to main content

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():

AssertionExample
Equalrm.expect(val).to.equal(200)
Includerm.expect(str).to.include('hello')
Have propertyrm.expect(obj).to.have.property('id')
Be a typerm.expect(val).to.be.a('string')
Be an arrayrm.expect(val).to.be.an('array')
Be truthyrm.expect(val).to.be.ok
Be nullrm.expect(val).to.be.null
Within rangerm.expect(val).to.be.within(1, 10)
Above / belowrm.expect(val).to.be.above(0)
Lengthrm.expect(arr).to.have.lengthOf(3)