Skip to content

Commit

Permalink
refactor: refactor user tests
Browse files Browse the repository at this point in the history
  • Loading branch information
leoferreiralima committed Sep 26, 2023
1 parent cac7403 commit 5893b5c
Show file tree
Hide file tree
Showing 5 changed files with 137 additions and 51 deletions.
7 changes: 7 additions & 0 deletions src/content/content.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
expectRequest,
mockOnceApiError,
mockOnceResponse,
mockOnceSession,
mockedRequest,
mockedRequests,
resetMocks,
Expand Down Expand Up @@ -168,8 +169,12 @@ describe('Content', () => {
};

it('should create content', async () => {
mockOnceSession();

mockCreateContent();

await tabNews.session.create();

const response = await tabNews.content.create({
slug: 'e-opcional',
title: 'test',
Expand All @@ -190,6 +195,8 @@ describe('Content', () => {
status: 'draft',
source_url: 'https://google.com',
});

expectRequest(request).cookie(TABNEWS_HEADERS.sessionId).toBeDefined();
});

it('should throw an error when create content with invalid parameters', () => {
Expand Down
7 changes: 4 additions & 3 deletions src/session/session.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ describe('Session', () => {

expectRequest(request).method.toBeDelete();
expectRequest(request)
.header(TABNEWS_HEADERS.cookie)
.toBe(`${TABNEWS_HEADERS.sessionId}=${session.token}`);
.cookie(TABNEWS_HEADERS.sessionId)
.toBe(session.token);
});

it('should throw an error when has no session', async () => {
Expand All @@ -107,7 +107,8 @@ describe('Session', () => {

const request = mockedRequest();

expectRequest(request).header(TABNEWS_HEADERS.cookie).toBeNull();
expectRequest(request).method.toBeDelete();
expectRequest(request).cookie(TABNEWS_HEADERS.sessionId).toBeUndefined();
});
});

Expand Down
26 changes: 26 additions & 0 deletions src/user/__snapshots__/user.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`User > me > should get me 1`] = `
{
"created_at": 2022-04-05T23:50:19.920Z,
"description": "description",
"email": "my@email.com",
"features": [
"create:session",
"read:session",
"create:content",
"create:content:text_root",
"create:content:text_child",
"update:content",
"update:user",
],
"id": "id",
"notifications": true,
"tabcash": 10,
"tabcoins": 9,
"updated_at": 2022-04-05T23:50:56.545Z,
"username": "username",
}
`;

exports[`User > me > should throw an error when has no session 1`] = `"Usuário não pode executar esta operação."`;
118 changes: 71 additions & 47 deletions src/user/user.spec.ts
Original file line number Diff line number Diff line change
@@ -1,65 +1,89 @@
import 'vitest-fetch-mock';

import { expect, describe, it, beforeEach } from 'vitest';
import { expect, describe, it, beforeEach, afterEach } from 'vitest';

import { TABNEWS_ENDPOINTS, TABNEWS_HEADERS } from '@/commons';
import { TabNews } from '@/tabnews';
import { createTabNews } from '@test/utils';
import {
createTabNews,
expectRequest,
mockOnceApiError,
mockOnceResponse,
mockOnceSession,
mockedRequest,
resetMocks,
} from '@test/utils';

let tabNews: TabNews;

const user = {
id: 'id',
username: 'username',
email: 'my@email.com',
description: 'description',
notifications: true,
features: [
'create:session',
'read:session',
'create:content',
'create:content:text_root',
'create:content:text_child',
'update:content',
'update:user',
],
tabcoins: 9,
tabcash: 10,
created_at: '2022-04-05T23:50:19.920Z',
updated_at: '2022-04-05T23:50:56.545Z',
};

describe('User', () => {
beforeEach(() => {
tabNews = createTabNews();
});

afterEach(() => {
resetMocks();
});

describe('me', () => {
it('should get me', async () => {
fetchMock.mockOnceIf(
(request) => request.url.endsWith('/user'),
JSON.stringify({
id: 'id',
username: 'username',
email: 'my@email.com',
description: 'description',
notifications: true,
features: [
'create:session',
'read:session',
'create:content',
'create:content:text_root',
'create:content:text_child',
'update:content',
'update:user',
],
tabcoins: 9,
tabcash: 10,
created_at: '2022-04-05T23:50:19.920Z',
updated_at: '2022-04-05T23:50:56.545Z',
}),
);

const user = await tabNews.user.me();

expect(user).toMatchObject({
id: 'id',
username: 'username',
email: 'my@email.com',
description: 'description',
notifications: true,
features: [
'create:session',
'read:session',
'create:content',
'create:content:text_root',
'create:content:text_child',
'update:content',
'update:user',
],
tabcoins: 9,
tabcash: 10,
created_at: new Date('2022-04-05T23:50:19.920Z'),
updated_at: new Date('2022-04-05T23:50:56.545Z'),
mockOnceSession();

mockOnceResponse(TABNEWS_ENDPOINTS.user, user);

await tabNews.session.create();

const me = await tabNews.user.me();

expect(me).toMatchSnapshot();

const request = mockedRequest();

expectRequest(request).method.toBeGet();

expectRequest(request).cookie(TABNEWS_HEADERS.sessionId).toBeDefined();
});

it('should throw an error when has no session', async () => {
mockOnceApiError(TABNEWS_ENDPOINTS.user, {
name: 'ForbiddenError',
message: 'Usuário não pode executar esta operação.',
action: 'Verifique se este usuário possui a feature "read:session".',
status_code: 403,
error_id: '1ca4236b-1a68-4573-acb8-40b220b2fd76',
request_id: 'c17c3107-8cce-4b35-b510-0c1b5b92e3b6',
error_location_code:
'MODEL:AUTHORIZATION:CAN_REQUEST:FEATURE_NOT_FOUND',
});

expect(() => tabNews.user.me()).rejects.toThrowErrorMatchingSnapshot();

const request = mockedRequest();

expectRequest(request).method.toBeGet();

expectRequest(request).cookie(TABNEWS_HEADERS.sessionId).toBeUndefined();
});
});
});
30 changes: 29 additions & 1 deletion test/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect } from 'vitest';
import { MockParams } from 'vitest-fetch-mock';

import { TABNEWS_ENDPOINTS } from '@/commons';
import { TABNEWS_ENDPOINTS, TABNEWS_HEADERS } from '@/commons';
import { TabNewsApiError } from '@/commons/interfaces';
import { TabNewsConfig } from '@/interfaces';
import { TabNews } from '@/tabnews';
Expand Down Expand Up @@ -64,6 +64,22 @@ export function mockedRequest() {
return request;
}

const parseCookie = (cookie: string | null) =>
!cookie
? {}
: cookie
.split(';')
.map((v) => v.split('='))
.reduce(
(acc, v) => {
acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(
v[1].trim(),
);
return acc;
},
{} as Record<string, string>,
);

export function expectRequest(request: Request) {
const url = new URL(request.url);

Expand All @@ -88,6 +104,17 @@ export function expectRequest(request: Request) {
toBeNull: () => expect(url.searchParams.get(parameter)).toBeNull(),
});

const cookie = (cookieName: string) => {
const cookies = parseCookie(request.headers.get(TABNEWS_HEADERS.cookie));

return {
toBe: (cookieValue: string) =>
expect(cookies[cookieName]).toBe(cookieValue),
toBeDefined: () => expect(cookies[cookieName]).toBeDefined(),
toBeUndefined: () => expect(cookies[cookieName]).toBeUndefined,
};
};

return {
body: {
toBe: toBodyBe,
Expand All @@ -99,6 +126,7 @@ export function expectRequest(request: Request) {
},
header,
query,
cookie,
};
}

Expand Down

0 comments on commit 5893b5c

Please sign in to comment.