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

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

describe('POST /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).post('/v1/fragments').auth('invalid@email.com', 'incorrect_password').expect(401));

  // Using a valid username/password pair should give a success result with a .fragments array
  test('authenticated users get a fragments array', async () => {
    const res = await request(app)
      .post('/v1/fragments')
      .auth('user1@email.com', 'password1')
      .send('fragment')
      .set('content-type', 'text/plain');
    expect(res.statusCode).toBe(201);
    expect(res.body.status).toBe('ok');
    expect(res.body.fragments != null).toBe(true);
  });

  test('authenticated users can create a plain text fragment', async () => {
	const data = Buffer.from('hello');
	const res = await request(app)
		.post('/v1/fragments')
		.auth('user1@email.com', 'password1')
		.set('Content-Type', 'text/plain')
		.send(data);

	expect(res.statusCode).toBe(201);
	expect(res.text.includes('text/plain'));
	});

  test('create a fragment with an unsupported type', async () => {
	const res = await request(app)
		.post('/v1/fragments')
		.auth('user1@email.com', 'password1')
		.set('Content-Type', 'invalid/abc');
	expect(res.statusCode).toBe(415);
	});

  //Successful POST method and return status code of 201 as well as the Location header of the response
	test('response include a Location header with a URL', async () => {
		const data = Buffer.from('hello');
		const res = await request(app)
			.post('/v1/fragments')
			.auth('user1@email.com', 'password1')
			.set('Content-Type', 'text/plain')
			.send(data);
		expect(res.statusCode).toBe(201);
    expect(res.headers.location.includes(`/v1/fragments/${res.body.fragments.id}`)).toBe(true);
	});
});