diff --git a/src/Tracker.ts b/src/Tracker.ts index 9f832e9..ef433b2 100644 --- a/src/Tracker.ts +++ b/src/Tracker.ts @@ -1,6 +1,6 @@ import cloneDeep from 'lodash.clonedeep'; import { FunctionQueryMatcher, QueryMatcher, RawQuery } from '../types/mock-client'; -import { queryMethods } from './constants'; +import { queryMethods, transactionCommands } from './constants'; export type TrackerConfig = Record; @@ -44,6 +44,10 @@ export class Tracker { public _handle(rawQuery: RawQuery): Promise { return new Promise((resolve, reject) => { setTimeout(async () => { + if (typeof rawQuery.method === 'undefined' && transactionCommands.includes(rawQuery.sql)) { + resolve(undefined); + } + const handlers = this.responses.get(rawQuery.method) || []; for (let i = 0; i < handlers.length; i++) { const handler = handlers[i]; diff --git a/src/constants.ts b/src/constants.ts index 9887f9c..fdeb8db 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -1 +1,3 @@ export const queryMethods = ['select', 'insert', 'update', 'delete'] as const; + +export const transactionCommands = ['BEGIN;', 'COMMIT;']; diff --git a/tests/insert.spec.ts b/tests/insert.spec.ts index a68d1f6..ec53e78 100644 --- a/tests/insert.spec.ts +++ b/tests/insert.spec.ts @@ -1,4 +1,4 @@ -import faker from 'faker'; +import * as faker from 'faker'; import knex, { Knex } from 'knex'; import { getTracker, MockClient } from '../src'; import { Tracker } from '../src/Tracker'; @@ -192,4 +192,17 @@ describe('mock Insert statement', () => { expect(tracker.history.insert).toHaveLength(1); expect(data).toEqual(3); }); + + it('should support transactions', async () => { + tracker.on.insert('table_name').responseOnce(1); + tracker.on.delete('table_name').responseOnce(1); + + await db.transaction(async (trx) => { + await db('table_name').insert({ name: faker.name.firstName() }).transacting(trx); + await db('table_name').delete().where({ name: faker.name.firstName() }).transacting(trx); + }); + + expect(tracker.history.insert).toHaveLength(1); + expect(tracker.history.delete).toHaveLength(1); + }); });