Last active
February 9, 2018 16:30
-
-
Save cange/2485085b2062da82839b40b88748b4b7 to your computer and use it in GitHub Desktop.
Mock a Ajax call with Jest test runner
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
class Feature { | |
load(url, callback) { | |
$.ajax({ url }) | |
.done((data) => { | |
callback.apply(this, [null, data]) | |
}) | |
.fail((jqXHR) => { | |
callback.apply(this, [jqXHR.statusText]) | |
}) | |
} | |
} |
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
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