0

I'm trying to mock my data access object using lowdb. But I'm not sure how to mock the collection based on my implementation.

AuthDao.ts

import { Injectable } from "@nestjs/common";
import { User } from "libs/api-interfaces/src/lib/api-interfaces";
import * as low from 'lowdb';
import * as FileSync from 'lowdb/adapters/FileSync';

  export interface MaintenanceRequestDB extends User {
    id: string;
    name: string;
  }

  export interface MaintenanceRequestData {
    users: MaintenanceRequestDB[];
  }

  const adapter = new FileSync<MaintenanceRequestDB>('./db/maint-requests.json')
  const db = low(adapter)
  
  db.defaults({ users: [] }).write();

@Injectable()
export class AuthDao {

    private get collection(): any {
            return db.get('users');
    }

    constructor(
    ) {
        //
    }

    async getAdminUsers(user: User): Promise<MaintenanceRequestDB> {
        const { username, password } = user;
        const values = await this.collection.find({
            username, password
    }).value();
        return values;
    }
}

Auth.Dao.Spec.TS

import { Test } from "@nestjs/testing";
import { User } from "libs/api-interfaces/src/lib/api-interfaces";
import { AuthDao } from "./auth.dao";


describe('AuthService', () => {
    let dao: AuthDao;
    beforeAll(async () => {
      const app = await Test.createTestingModule({
        providers: [AuthDao],
      }).compile();
      dao = app.get<AuthDao>(AuthDao);
    });
  
    describe('getData', () => {
      it('should return valid user', async () => {
         
         const result = await dao.getAdminUsers(createUser("johndoe", "123456"));
         expect(result).toEqual({username: 'johndoe'});
      });
    });
  });

  function createUser(username: string, password: string): User {
    return ({
      username: username,
      password: password
    })
}

Also since I use createUser function almost in every test, where and how can I refactor my code so that it can be use with other tests?

Yzak
  • 81
  • 2
  • 13

1 Answers1

0

I added two database to prevent iterating the real database, one holds the data to seed and the other the seeded database to use for unit test.

import { seedDatabase} from "../../../database";
beforeAll(async () => {
        seedDatabase();
    });

then defined the database.ts

const databaseFile = path.join(__dirname, "../db/test-db.json");
const adapter = new FileSync<MaintenanceRequestDB>(databaseFile);
const db = low(adapter);
export const seedDatabase = () => {
    const testSeed = JSON.parse(
      fs.readFileSync(path.join(process.cwd(), "db", "test-db-seed.json"), "utf-8")
    );
  
    // seed database with test data
    db.setState(testSeed).write();
    return;
  };

I thought you need spyOn or jest to mock the db, I guess you just need to load the db again.

Yzak
  • 81
  • 2
  • 13