Skip to content

Commit

Permalink
feat: add transactions support
Browse files Browse the repository at this point in the history
  • Loading branch information
felixmosh committed May 11, 2021
1 parent 516a3a0 commit 0ed045e
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
6 changes: 5 additions & 1 deletion src/Tracker.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>;

Expand Down Expand Up @@ -44,6 +44,10 @@ export class Tracker {
public _handle(rawQuery: RawQuery): Promise<any> {
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];
Expand Down
2 changes: 2 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export const queryMethods = ['select', 'insert', 'update', 'delete'] as const;

export const transactionCommands = ['BEGIN;', 'COMMIT;'];
15 changes: 14 additions & 1 deletion tests/insert.spec.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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);
});
});

0 comments on commit 0ed045e

Please sign in to comment.