Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to inspect query fragments without database connection #816

Open
wms opened this issue Feb 23, 2024 · 1 comment
Open

Ability to inspect query fragments without database connection #816

wms opened this issue Feb 23, 2024 · 1 comment

Comments

@wms
Copy link

wms commented Feb 23, 2024

Thanks for building this library, it's very impressive and I'm enjoying using it so far.

It would be very helpful if I could unit test some of my query-generating functions without the need for a DB connection. For example, with an .inspect() method or similar that returns a simple {text, values} structure or similar without inducing a DB round-trip.

There appears to be some discussion around this requirement in #760 and the current workaround appears to be to catch the exception and then inspect the query and parameters properties on the exception, which may not be ideal.

@t-d-d
Copy link

t-d-d commented Mar 22, 2024

I am using below for mocking with jest. Only a start and only covers part of the api but I have used to unit test some of my code.

import sql from "./db";
jest.mock('./db');
const parseQuery = ([segments, ...params]) => typeof segments === 'string' ? segments : segments.reduce((a, v, i) => `${a}${v}${params[i] ?? ''}`, '')
sql.mockImplementation(s => typeof s === 'string' ? s : [])

it("a test", () => {
  ...
  const query = parseQuery(sql.mock.lastCall)
  const [_, ...values] = sql.mock.lastCall
  ...
}

I also mock sql.begin to capture statements per transaction:

  sql.tx = []
  sql.begin = jest.fn(func => {
    const txMockSql = jest.fn(sql)
    sql.tx.push(txMockSql)
    return func(txMockSql)
  })
  ...
  expect(parseQuery(sql.tx[0].mock.lastCall)).toMatch(/SELECT somesqlintx0/)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants