Skip to content

Instantly share code, notes, and snippets.

@mmrko
Last active August 10, 2016 08:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmrko/ff9a9efb9857a90595db to your computer and use it in GitHub Desktop.
Save mmrko/ff9a9efb9857a90595db to your computer and use it in GitHub Desktop.
Mock AmpersandJS sync for tests (Mocha & Sinon)
import BaseModel from 'ampersand-model'
import BaseCollection from 'ampersand-collection'
import sync from 'ampersand-sync'
const xhrImplementation = xhrOptions => {
xhrOptions.success && xhrOptions.success.call(null, {})
return {}
}
BaseModel.prototype.sync = BaseCollection.prototype.sync = (method, model, options = {}) => {
options.xhrImplementation = options.xhrImplementation || xhrImplementation
sync.call(null, method, model, options)
}
import cloneDeep from 'lodash.clonedeep'
import { stub } from 'sinon'
/**
* Mock AJAX requests by passing a custom xhr implementation to Model/Collection.sync()
*
* @param {Object} modelOrCollection Ampersand Model/Collection
* @param {Object} data Mock data object for success/error response
* @returns {Object} Sinon stub
*
*/
export default function mockXhr (modelOrCollection, data = {}) {
const sync = modelOrCollection.sync
return stub(modelOrCollection, 'sync', (method, model, options = {}) => {
options.xhrImplementation = xhrOptions => {
const xhrCallback = data.error ? xhrOptions.error : xhrOptions.success
xhrCallback.call(null, cloneDeep(data.error) || cloneDeep(data.success) || {})
return {}
}
sync.call(this, method, model, options)
})
}
mocha --compilers js:babel-core/register ./ampersand-mock-sync *.spec.js
import BaseModel from 'ampersand-model'
import BaseCollection from 'ampersand-collection'
import mockXhr from './ampersand-mock-xhr'
const Model = BaseModel.extend({
url: 'http://localhost/foo'
})
const Collection = BaseCollection.extend({
model: Model
})
let collection, stubCollection
before(() => {
collection = new Collection()
stubCollection = mockXhr(collection, { success: [ { foo: 'bar' }, { foo: 'baz' } ] )
})
after(() => {
stubCollection.restore()
})
it('should return a mocked response', () => {
collection.fetch()
setTimeout(() => {
expect(collection).to.have.length(2)
expect(collection.at(0).foo).to.equal('bar')
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment