Created
December 14, 2016 09:43
-
-
Save tothandras/e7576028aff91f98cdc4b9022d39b304 to your computer and use it in GitHub Desktop.
knex model mocking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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' }) | |
}) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const knex = require('./knex') | |
const tableName = 'user' | |
const User = { | |
getOne (userId) { | |
return knex(tableName) | |
.where({ id: userId }) | |
.first() | |
} | |
} | |
module.exports = User |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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