fragments / tests / unit / put.test.js
put.test.js
Raw
const request = require('supertest');

const app = require('../../src/app');

describe('PUT /v1/fragments', () => {
    // If the request is missing the Authorization header, it should be forbidden
    test('unauthenticated requests are denied', () => request(app).post('/v1/fragments').expect(401));

    // If the wrong username/password pair are used (no such user), it should be forbidden
    test('incorrect credentials are denied', () =>
        request(app).put('/v1/fragments').auth('invalid@email.com', 'incorrect_password').expect(401));

    test('authenticated user update fragment using PUT but wrong old type', async () => {
        const resPost = await request(app)
        .post('/v1/fragments')
        .auth('user1@email.com', 'password1')
        .set('Content-Type', 'text/plain')
        .send('fragment');

        const id = resPost.body.fragments.id;

        const res = await request(app)
        .put(`/v1/fragments/${id}`)
        .auth('user1@email.com', 'password1')
        .send('new fragment')
        .set('content-type', 'text/markdown');
        expect(res.statusCode).toBe(400);
        expect(res.body.status).toBe('error');
    });

    test('if invalid id, returns 404 error', async () => {
		const putRes = await request(app)
			.put('/v1/fragments/abc')
			.auth('user1@email.com', 'password1')
			.set('Content-Type', 'text/plain')
			.send('This is updated fragment');

		expect(putRes.statusCode).toBe(404);
	});

    test('if authenticated user put unsupported type', async () => {
		const putRes = await request(app)
			.put('/v1/fragments/abc')
			.auth('user1@email.com', 'password1')
			.set('Content-Type', 'abc')
			.send('This is updated fragment');

		expect(putRes.statusCode).toBe(415);
	});

    test('authenticated user update fragment using PUT method to update fragment successfully', async () => {
        const resPost = await request(app)
        .post('/v1/fragments')
        .auth('user1@email.com', 'password1')
        .set('Content-Type', 'text/plain')
        .send('this is fragment');

        const id = resPost.body.fragments.id;

        const res = await request(app)
        .put(`/v1/fragments/${id}`)
        .auth('user1@email.com', 'password1')
        .send('this is updated fragment')
        .set('content-type', 'text/plain');
        expect(res.statusCode).toBe(200);
        expect(res.body.status).toBe('ok');
        expect(res.body.fragments != null).toBe(true);
    });
});