Hello guys. Can someone review my unit tests?
I'm a beginner to unit tests and for now this doesn't make sense to me, but maybe it's not so bad 😄
import { TestBed } from "@automock/jest";
import { BadRequestException } from "@nestjs/common";
const mockBook: Book = {} // some object with mock data
const mockBooks: Book[] = [mockBook, mockBook];
describe("Book service", () => {
let service: BooksService;
let getBookByBookIdApi: jest.Mocked<GetBookByBookIdApi>;
const getBookQuery: GetBookQuery = {
brand: "bookBrand",
bookId: "oaeifn123aeklgfn",
};
beforeAll(() => {
const { unit, unitRef } = TestBed.create(BooksService).compile();
service = unit;
getBookByBookIdApi = unitRef.get(GetBookByBookIdApi);
jest.clearAllMocks();
});
it("Should be defined", () => {
expect(service).toBeDefined();
});
describe("getBookByBookId", () => {
it("Should return BadRequestException", async () => {
expect(
service.getBookByBookId({
brand: "",
}),
).rejects.toBeInstanceOf(BadRequestException);
});
it("Should return null", async () => {
getBookByBookIdApi.execute.mockResolvedValue(null);
const Books = await service.getBookByBookId(getBookQuery);
expect(getBookByBookIdApi.execute).toHaveBeenCalledWith({
bookId: getBookQuery.bookId,
});
expect(Books).toEqual(null);
});
it("Should return a Book", async () => {
jest.spyOn(getBookByBookIdApi, "execute").mockResolvedValue(mockBook);
const Book = await service.getBookByBookId(getBookQuery);
expect(getBookByBookIdApi.execute).toHaveBeenCalledWith({
bookId: getBookQuery.bookId,
});
expect(Book).toEqual(mockBook);
});
});
});
// GetBookByBookIdApi.ts
/*
in this file is only a http get request
*/
// ... the rest of the code
execute({bookId}: string) {
// ... the rest of the code
return await this.httpService.request<Book[]>(config);
}