0
//insertRecord.ts
import {knexInstance} from './logDatabaseConfig';

const insertLog = async(quan: Number) => {

    try {
        await knexInstance('LOG')
        .insert({sync_quantity: quan, sync_at: new Date()});
    } catch (error) {
    throw new Error('Error insert' + error);
    }  

}

export default insertLog;

import { expect } from '@jest/globals';
import knex, { Knex } from 'knex';
import { Tracker, getTracker, MockClient } from 'knex-mock-client';
import { faker } from '@faker-js/faker';
import insertLog from './insertLog';


jest.mock('./insertLog', () => {
    return {
      db: knex({ client: MockClient })
    };
});


describe('log insert tests', () => {
    let tracker: Tracker;
  
    beforeAll(() => {
      tracker = getTracker();
    });
  
    afterEach(() => {
      tracker.reset();
    });
  
    it('should add new log record', async () => {
     
      tracker.on.insert('LOG');
      
      
      const syncQuantity = 1;
      await insertLog(1);
  
  
      const insertHistory = tracker.history.insert;
  
      expect(insertHistory).toHaveLength(1);
      expect(insertHistory[0].method).toEqual('insert');
    });
  });

Question about knex-mock-client

My dependencies "@faker-js/faker": "^7.2.0", "@types/jest": "^28.1.1", "concurrently": "^7.2.1", "jest": "^28.1.1", "knex-mock-client": "^1.8.4", "nodemon": "^2.0.16", "ts-jest": "^28.0.4"

TypeError: (0 , insertLog_1.default) is not a function and highlighting - await insertLog(1);

Anyone got the same issue?

J L
  • 67
  • 2
  • 8
  • The test double doesn't make sense - the real module exposes an `insertLog` function that returns `Promise` as the default export, but your mock implementation is an object with a `db` property. – jonrsharpe Jun 08 '22 at 09:48
  • https://stackoverflow.com/questions/28165063/how-can-i-mock-a-fake-database-for-when-unit-testing-against-knex just based on this answer – J L Jun 08 '22 at 10:05

1 Answers1

0

finally fixed that, able to mock the database to test the database module

describe('insert log test', () => {
    let tracker: any;
    const mockDataConn = knex(dummyDbConn);
    tracker = getTracker();
  
    it('should add new log record', async () => {
      const insertId = faker.datatype.number();
      tracker.on.insert('DATA_SYNC_LOG').response([insertId]);
      
      const syncQuantity = 1;
      const syncDate = new Date();
      await insertLog(mockDataConn, syncQuantity, syncDate);
  
      const insertHistory = tracker.history.insert;
  
      //number of record wrote
      expect(insertHistory).toHaveLength(1);

      //SQL method insert/create/update/delete
      expect(insertHistory[0].method).toEqual('insert');
      
      //compare record inserted
      expect(insertHistory[0].bindings).toEqual([ syncDate, syncQuantity]);
    });

    tracker.reset();
  });
J L
  • 67
  • 2
  • 8