Created
August 4, 2016 00:43
-
-
Save mrparkers/b38f34e0355fc07d805b26795d28ffe6 to your computer and use it in GitHub Desktop.
Unit testing an async React component using Mocha, Chai, and Enzyme
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 AsyncComponent from './path/to/component'; | |
import request from 'your-request-library'; | |
import React from 'react'; | |
import {shallow} from 'enzyme'; | |
import Chance from 'chance'; | |
import chai, {expect} from 'chai'; | |
import sinon from 'sinon'; | |
import sinonChai from 'sinon-chai'; | |
describe('Async Component', () => { | |
let renderedElement, | |
renderedInstance, | |
fakePromise, | |
fakePromiseResolve, | |
sandbox, | |
chance; | |
function renderComponent() { | |
const componentElement = React.createElement(AsyncComponent); | |
renderedElement = shallow(componentElement); | |
renderedInstance = renderedElement.instance(); | |
} | |
before(() => { | |
chai.use(sinonChai); | |
}); | |
beforeEach(() => { | |
chance = new Chance(); | |
sandbox = sinon.sandbox.create(); | |
renderComponent(); | |
fakePromise = new Promise(resolve => { | |
fakePromiseResolve = resolve; | |
}); | |
sandbox.stub(request, 'get').returns(fakePromise); | |
sandbox.stub(renderedInstance, 'setState'); | |
}); | |
afterEach(() => { | |
sandbox.restore(); | |
}); | |
describe('Given the component was mounted to the DOM', () => { | |
beforeEach(() => { | |
renderedInstance.componentDidMount(); | |
}); | |
it('should send a request to the server', () => { | |
expect(request.get).to.have.callCount(1); | |
expect(request.get).to.be.calledWith('/some/url/that/returns/my/data'); | |
}); | |
describe('Given the request completed successfully', () => { | |
let fakeResponse; | |
beforeEach(done => { | |
fakeResponse = { | |
records: chance.string() | |
}; | |
fakePromise.then(() => { | |
done(); | |
}); | |
fakePromiseResolve(fakeResponse); | |
}); | |
it('should set the component state with the result', () => { | |
expect(renderedInstance.setState).to.have.callCount(1); | |
expect(renderedInstance.setState).to.be.calledWith({ | |
records: fakeResponse.records | |
}); | |
}); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment