|
- import {describe, it, expect, vi, Mock, beforeAll, beforeEach} from 'vitest';
- import { readFile, writeFile } from 'fs/promises';
- import { JsonLinesDataSource } from '../src';
- import { resource, validation as v } from '@modal-sh/yasumi';
- import {DataSource} from '@modal-sh/yasumi/dist/types/backend';
-
- vi.mock('fs/promises');
-
- describe('prepareResource', () => {
- beforeAll(() => {
- const mockWriteFile = writeFile as Mock;
- mockWriteFile.mockImplementation(() => { /* noop */ })
- });
-
- it('works', () => {
- const schema = v.object({});
- const r = resource(schema);
- const ds = new JsonLinesDataSource<typeof schema>();
- expect(() => ds.prepareResource(r)).not.toThrow();
- });
- });
-
- describe('methods', () => {
- const dummyItems = [
- {
- id: 1,
- name: 'foo',
- },
- {
- id: 2,
- name: 'bar',
- },
- {
- id: 3,
- name: 'baz',
- },
- ];
- const schema = v.object({
- name: v.string(),
- });
- let ds: DataSource<v.Output<typeof schema>>;
- let mockGenerationStrategy;
- beforeEach(() => {
- mockGenerationStrategy = vi.fn();
- const r = resource(schema)
- .id('id', {
- generationStrategy: mockGenerationStrategy,
- schema: v.any(),
- serialize: (id) => id.toString(),
- deserialize: (id) => Number(id.toString()),
- });
- ds = new JsonLinesDataSource<typeof schema>();
- ds.prepareResource(r);
- });
-
- beforeEach(() => {
- const mockReadFile = readFile as Mock;
- mockReadFile.mockReturnValueOnce(
- dummyItems.map((i) => JSON.stringify(i)).join('\n')
- );
- });
-
- describe('initialize', () => {
- it('works', async () => {
- try {
- await ds.initialize();
- } catch {
- expect.fail('Could not initialize data source.');
- }
- });
- });
-
- describe('operations', () => {
- beforeEach(async () => {
- await ds.initialize();
- });
-
- describe('getTotalCount', () => {
- it('works', async () => {
- if (typeof ds.getTotalCount !== 'function') {
- return;
- }
- const totalCount = await ds.getTotalCount();
- expect(totalCount).toBe(dummyItems.length);
- });
- });
-
- describe('getMultiple', () => {
- it('works', async () => {
- const items = await ds.getMultiple();
- expect(items).toEqual(dummyItems);
- });
- });
-
- describe('getById', () => {
- it('works', async () => {
- const item = await ds.getById('2');
- const expected = dummyItems.find((i) => i.id === 2);
- expect(item).toEqual(expected);
- });
- });
-
- describe('getSingle', () => {
- it('works', async () => {
- if (typeof ds.getSingle !== 'function') {
- return;
- }
- const item = await ds.getSingle();
- const expected = dummyItems[0];
- expect(item).toEqual(expected);
- });
- });
-
- describe.todo('create');
- describe.todo('delete');
- describe.todo('emplace');
- describe.todo('patch');
-
- describe('newId', () => {
- it('works', async () => {
- const v = 'newId';
- mockGenerationStrategy.mockResolvedValueOnce(v);
- const id = await ds.newId();
- expect(id).toBe(v);
- });
- });
- });
- });
|