REST
Common tests for REST APIs
Features of this Example
Basic authentication
Storing and Reading Environment Variables in Asserted
Test the list, create, get, update, and remove REST endpoints
Walkthrough
This example was referenced in a walkthrough about Node API Health Checks and Uptime
Try it out
Repo is available here.
# Clone example
git clone https://github.com/assertedio/node-uptime
# Enter directory and install
cd graphql-uptime/
npm install
# Run asserted tests
npm run test:asrtd
Tests
Can also be viewed on github here.
const { expect } = require('chai');
const got = require('got');
const getenv = require('getenv');
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, './.env') });
const TOKEN = getenv('TOKEN');
const client = got.extend({
prefixUrl: 'http://localhost:3000',
headers: { authorization: TOKEN },
});
describe('node api tests', () => {
let userId;
it('get all users', async () => {
const { data } = await client.get('users').json();
expect(data.length).to.eql(4);
});
it('create user', async () => {
const { data } = await client.post('users', { json: { name: 'Foo Bario', email: '[email protected]' }}).json();
const { id, name, email } = data;
userId = id;
expect(userId).to.exist;
expect(name).to.eql('Foo Bario');
expect(email).to.eql('[email protected]');
});
it('get user', async () => {
expect(userId).to.exist;
const { data } = await client.get('users/' + userId).json();
const { id, name, email } = data;
expect(id).to.eql(userId);
expect(name).to.eql('Foo Bario');
expect(email).to.eql('[email protected]');
});
it('update user', async () => {
expect(userId).to.exist;
const { data } = await client.put('users/' + userId, { json: { name: 'Bar Yaz', email: '[email protected]' }}).json();
const { id, name, email } = data;
expect(id).to.eql(userId);
expect(name).to.eql('Bar Yaz');
expect(email).to.eql('[email protected]');
});
it('remove user', async () => {
expect(userId).to.exist;
await client.delete('users/' + userId).json();
const { data } = await client.get('users/' + userId).json();
expect(data).to.eql(null);
});
});
Last updated
Was this helpful?