Skip to content

Instantly share code, notes, and snippets.

@cange
Last active February 9, 2018 16:30
Show Gist options
  • Save cange/2485085b2062da82839b40b88748b4b7 to your computer and use it in GitHub Desktop.
Save cange/2485085b2062da82839b40b88748b4b7 to your computer and use it in GitHub Desktop.
Mock a Ajax call with Jest test runner
class Feature {
load(url, callback) {
$.ajax({ url })
.done((data) => {
callback.apply(this, [null, data])
})
.fail((jqXHR) => {
callback.apply(this, [jqXHR.statusText])
})
}
}
import Feature from './Feature'
describe('Feature', () => {
const fakeData = { x: 0, y: 0 }
let subject
let callback
beforeEach(() => {
callback = jest.fn()
$.ajax = jest.fn(() => {
let deferred = $.Deferred()
deferred.resolve(fakeData)
return deferred.promise()
})
subject = new Feature()
})
it('loads JSON data', () => {
url = 'load_path'
subject.load(url, callback)
expect($.ajax).toHaveBeenCalledWith({ url })
})
it('calls callback when successful', () => {
expect(callback).toHaveBeenCalledWith(null, fakeData)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment