Skip to content

Instantly share code, notes, and snippets.

@tothandras
Created December 14, 2016 09:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tothandras/e7576028aff91f98cdc4b9022d39b304 to your computer and use it in GitHub Desktop.
Save tothandras/e7576028aff91f98cdc4b9022d39b304 to your computer and use it in GitHub Desktop.
knex model mocking
'use strict'
const expect = require('chai').expect
const objectid = require('objectid')
const request = require('super-request')
const User = require('./user')
const server = require('./server') // your http server
describe('GET /api/v1/user/:userId', () => {
let userId
beforeEach(function * () {
userId = objectid().toString()
})
it('should return a user', function * () {
this.sandbox.stub(User, 'getOne', function () {
return Promise.resolve({ id: userId, name: 'User Name' })
})
const response = yield request(server.listen())
.get(`/api/v1/user/${userId}`)
.json(true)
.expect(200)
.end()
expect(Check.get).to.have.been.calledWith(userId)
expect(response.body).to.eql({ id: userId, name: 'User Name' })
})
})
'use strict'
const knex = require('./knex')
const tableName = 'user'
const User = {
getOne (userId) {
return knex(tableName)
.where({ id: userId })
.first()
}
}
module.exports = User
'use strict'
const objectid = require('objectid')
const knex = require('./knex')
const User = require('./user')
describe(`${User.tableName} table`, () => {
// co-mocha for generator functions
it('should exist', function * () {
const exists = yield knex.schema.hasTable(User.tableName)
expect(exists).to.be.true
})
describe('functions', () => {
let user
beforeEach(function * () {
user = {
id: objectid().toString(),
name: 'Super User'
// ...
}
yield knex(User.tableName)
.insert(user)
})
afterEach(function * () {
yield knex(User.tableName)
.where({ id: user.id })
.delete()
})
it('should return a user', function * () {
const resp = yield User.getOne(user.id)
expect(resp).to.eql(user)
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment