How to test knex query builder with jest/unit test?

Viewed 22

I have a function written with knex. (SQL query builder) in nodejs.

export const queryProducts = (query) => {
  const products = knex('db').from('product').select('id', 'name').where('name', 'like', query.term);

  return products;
}

Knex is creating SQL query and running it in the SQL server and returns the results.

How do I write unit tests for this function? Should I mock knex? but knex is performing a logic operation (where) so it's not just return an { object } because the query can be change over the time to some other query.

So I think I must running the query in the db in order to test and check if the fields are exist and the results are correct.

But it's a unit test. so does how all of this make any sense?

1 Answers

Your solution is nice enough! create a separate database, migrate on "before", run your tests and remove database on "after".

another way is to put your query in separate method and stub that.

export const queryProducts = async (query) => {
  const products = await getProducts(query.term)
  // some other stuff
  return products;
}

export const getProducts = async (term) => {
  return knex('db').from('product').select('id', 'name').where('name', 'like', term);
}

now you can stub getProducts and return what you want for different senarios.

Related