Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest mock Knex transaction

I have the following lambda handler to unit test. It uses a library @org/aws-connection which has a function mysql.getIamConnection which simply returns a knex connection.

Edit: I have added the mysql.getIamConnection function to the bottom of the post

Edit: If possible, I'd like to do the testing with only Jest. That is unless it becomes to complicated

index.js

const {mysql} = require('@org/aws-connection');

exports.handler = async (event) => {
  const connection = await mysql.getIamConnection()

  let response = {
    statusCode: 200,
    body: {
      message: 'Successful'
    }
  }

  try {
    for(const currentMessage of event.Records){
      let records = JSON.parse(currentMessage.body);
      
      await connection.transaction(async (trx) => {
        await trx
            .table('my_table')
            .insert(records)
            .then(() =>
                console.log(`Records inserted into table ${table}`))
            .catch((err) => {
                console.log(err)
                throw err
            })
      })
    }
  } catch (e) {
    console.error('There was an error while processing', { errorMessage: e})

    response = {
      statusCode: 400,
      body: e
    }
  } finally {
    connection.destroy()
  }
  return response
}

I have written some unit tests and I'm able to mock the connection.transaction function but I'm having trouble with the trx.select.insert.then.catch functions. H

Here is my testing file index.test.js

import { handler } from '../src';
const mocks = require('./mocks');

jest.mock('@org/aws-connection', () => ({
    mysql: {
        getIamConnection: jest.fn(() => ({
            transaction: jest.fn(() => ({
                table: jest.fn().mockReturnThis(),
                insert: jest.fn().mockReturnThis()
            })),
            table: jest.fn().mockReturnThis(),
            insert: jest.fn().mockReturnThis(),
            destroy: jest.fn().mockReturnThis()
        }))
    }
}))

describe('handler', () => {
    test('test handler', async () =>{
      const response = await handler(mocks.eventSqs)
      expect(response.statusCode).toEqual(200)
    });
});

This test works partially but it does not cover the trx portion at all. These lines are uncovered

await trx
        .table('my_table')
        .insert(records)
        .then(() =>
            console.log(`Records inserted into table ${table}`))
        .catch((err) => {
            console.log(err)
            throw err
        })

How can set up my mock @org/aws-connection so that it covers the trx functions as well?

Edit: mysql.getIamConnection

async function getIamConnection (secretId, dbname) {
    const secret = await getSecret(secretId)

    const token = await getToken(secret)

    let knex
    console.log(`Initialzing a connection to ${secret.proxyendpoint}:${secret.port}/${dbname} as ${secret.username}`)
    knex = require('knex')(
        {
            client: 'mysql2',
            connection: {
                host: secret.proxyendpoint,
                user: secret.username,
                database: dbname,
                port: secret.port,
                ssl: 'Amazon RDS',
                authPlugins: {
                    mysql_clear_password: () => () => Buffer.from(token + '\0')
                },
                connectionLimit: 1
            }
        }
    )

    return knex
}

Solution

@qaismakani's answer worked for me. I wrote it slightly differently but the callback was the key. For anyone interested here is my end solution

const mockTrx = {
    table: jest.fn().mockReturnThis(),
    insert: jest.fn().mockResolvedValue()
}

jest.mock('@org/aws-connection', () => ({
    mysql: {
        getIamConnection: jest.fn(() => ({
            transaction: jest.fn((callback) => callback(mockTrx)),
            destroy: jest.fn().mockReturnThis()
        }))
    }
}))
like image 941
navig8tr Avatar asked Oct 14 '22 21:10

navig8tr


2 Answers

Okay, let's see. Updating your mock to look like this might do the trick:


const {mysql} = require('@org/aws-connection');
jest.mock('@org/aws-connection', () => ({
    mySql: {
        getIamConnection: jest.fn()
    }
}));


const mockTrx = {
  table: jest.fn().mockReturnThis(),
  insert: jest.fn().mockResolveValue() // resolve any data here
};
mysql.getIamConnection.mockReturnValue({
    transaction: jest.fn((callback) => callback(mockTrx)),
});

Edit: Explanation

You need to mock transaction in a way that it calls your callback with a dummy trx. Now to get the dummy trx right, you need to make sure that all the functions inside dummy trx object return a reference back to it or a promise so that you can chain it appropriately.

like image 85
qaismakani Avatar answered Oct 18 '22 08:10

qaismakani


Instead of mocking knex implementation, I've written knex-mock-client which allows you to mimic real db with an easy API.

Change your mock implementation with

import { handler } from "../src";
import { getTracker } from "knex-mock-client";
const mocks = require("./mocks");

jest.mock("@org/aws-connection", () => {
  const knex = require("knex");
  const { MockClient } = require("knex-mock-client");
  return {
    mysql: {
      getIamConnection: () => knex({ client: MockClient }),
    },
  };
});

describe("handler", () => {
  test("test handler", async () => {
    const tracker = getTracker();
    tracker.on.insert("my_table").responseOnce([23]); // setup's a mock response when inserting into my_table

    const response = await handler(mocks.eventSqs);
    expect(response.statusCode).toEqual(200);
  });
});
like image 28
felixmosh Avatar answered Oct 18 '22 09:10

felixmosh