npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@nearform/no-gres

v3.0.0

Published

Mock pg-node for testing

Downloads

2,531

Readme

No-Gres

A small module to mock pg for testing purposes.

Greenkeeper badge js-standard-style

  • Includes support for async/await, promise and callback styles.
  • Verifies that all expected sql statements are called, and with matching parameters
  • Verifies sql statements are called in the correct sequence
  • Can strict match sql string equality or use regular expressions
  • Allows return values for each statement to be defined
  1. Install
  2. Usage
  3. API
  4. Example Code

Install

npm install --save-dev @nearform/no-gres

Usage

const assert = require('assert')
const Client = require('@nearform/no-gres').Client
const fetchCustomer = require('./fetchCustomer')

const doTest = async () => {
  const dbClient = new Client()

  // Set expectations and result
  dbClient.expect(
    /SELECT firstname, lastname FROM customer WHERE id = \$1/i,
    [2],
    [
      { firstname: 'Jayne', lastname: 'Cobb' }
    ])
  // Returns the parameters passed so that they can be used for assertions or more expecations

  await dbClient.connect() // Queries will error if this is not called first
  const result = await fetchCustomer.fetchCustomerById(dbClient, 2)

  dbClient.done() // Check all expectations are met - will error if not

  // Assert results
  assert.deepStrictEqual(result, ['Jayne Cobb'])
}

module.exports = doTest

API

constructor

const Client = new noGres.Client()

throwOnConnect(err)

Client.errorOnConnect(new Error('Unknown  Host'))

Used to simulate an error during connection. The error supplied will be either throw or used in promise rejection, depending on how connect is called.

connect([callback])

This must be called before any queries happen, which follows the behaviour of the real pg api. You can make this simulate an error (e.g. to test error handling) by use of the throwOnConnect method.

// callback
Client.connect((err) => {
    console.error(err)
    // ...do stuff
})

// promise
Client.connect()
.catch((err) => {
    console.error(err)
})
.then(() => {
    // ...do stuff
}

// async
try {
    await Client.connect()
} catch(err) {
    console.error(err)
}
// ...do stuff

expect(sql, [params], [returns])

This sets an expectation that a call will be made to the query function of the client. It can be called multiple times to set a sequence of expectations. Any unmatched call or a call out of sequence will cause the query call to generate an error.

sql - A string or regular expression which will be compared to the string passed to the query function

params - An optional array of parameters which will be matched against those passed to the query function

returns - An optional array or an Error instance. If an array, it will represent the "rows" to be returned by the query call. If an Error, the associated query will fail with this error. By default, an empty rowset is returned.

Returns the parameters used on the call as an objects. Handy for re-using the values later in the test:

const { sql, params, returns } = client.expect('select * from orders where id = $1', [123], [])
client.expect(sql, [456], [{id: 456}])
client.expect(sql, params, returns)

let res
res = await orders.fetchById(client, 123)
assert.deepStrictEqual(res, [])
res = orders.fetchById(client, 456)
assert.deepStrictEqual(res, [456])
res = await orders.fetchById(client, 123)
assert.deepStrictEqual(res, [])

query (sql, params, [callback])

query (config, [callback])

Mock of the pg query function. sql - sql statement to run params - parameter array for the sql callback - optional (err, data) callback. If not supplied, a promise will be returned. config - object containing text and values for the sql and parameters, respectively. Used for compatibility with the real api.

const order = await client.query('select * from orders where id = $1, [123])

const product = client.query({
    text: 'select * from products where category = $1',
    values: ['games']
    }, (err, data) => {
        if (err) {
            return console.error(err)
        }
        return data
    })

done()

Verifies that all expectations have been met. Will throw an error if they have not.

await client.expect(/select/, [])
client.done()

//Error: Unresolved expectations: [
//  {
//    "sql": {},
//    "params": [],
//    "returns": []
//  }
//]

reset()

Removes all pending expectations and allows the client to be re-used

client.expect(/select/, [])
client.reset()
client.done()

Example Code

See the example directory of this project for sample code testing a module against both no-gres and a real PG client instance.

License

Copyright nearForm Ltd 2018. Licensed under Apache 2.0.