Add tests for the API class

This commit is contained in:
Stedoss 2022-11-01 21:26:03 +00:00
parent ba4771614d
commit 553e4f3461

View File

@ -0,0 +1,73 @@
import { expect, jest, describe, it } from '@jest/globals';
import { API } from '../lib/api';
import { TCategory, TTag } from '../lib/types';
function createFetchMock<T>(returnValue: T) {
global.fetch = jest.fn((): Promise<any> => {
return Promise.resolve({
json: () => Promise.resolve(returnValue)
});
});
}
describe("Given the API", () => {
describe("when it is calling the category endpoint", () => {
it("should return a list of categories", async () => {
const api = new API("");
const categories: TCategory[] = [
{
id: 1,
name:"category_one"
},
{
id: 2,
name:"category_two"
},
{
id: 3,
name:"category_three"
}
];
createFetchMock<TCategory[]>(categories);
const categoriesResponse = await api.getCategories();
expect(categoriesResponse).toHaveLength(3);
expect(categoriesResponse[0]).toEqual(categories[0]);
expect(categoriesResponse[1]).toEqual(categories[1]);
expect(categoriesResponse[2]).toEqual(categories[2]);
});
});
describe("when it is calling the tag endpoint", () => {
it("should return a list of categories", async () => {
const api = new API("");
const tags: TTag[] = [
{
id: 1,
name:"tag_one"
},
{
id: 2,
name:"tag_two"
},
{
id: 3,
name:"tag_three"
}
];
createFetchMock<TTag[]>(tags);
const tagsResponse = await api.getTags();
expect(tagsResponse).toHaveLength(3);
expect(tagsResponse[0]).toEqual(tags[0]);
expect(tagsResponse[1]).toEqual(tags[1]);
expect(tagsResponse[2]).toEqual(tags[2]);
});
});
});