Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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