unit testing with react · • global.window =global.document.defaultview; sample project
TRANSCRIPT
Unit Testing With ReactEmrah Öz
Akbank T.A.Ş.
Why Unit Test
• So many reasons.
• Reduces bug. Not may be now , future is guaranteed.
• Helps for documentation.
• Test helps you to refactor
• Fun if you enjoy it J
• Testing slows down you for thinking.
• Reduces production fears (strong product)
• Etc…
TDD (Test Driven Development)
• When I click the button onClick should have called.
BDD (Behaviour Driven Development)
• Behavior-driven development (BDD) is a software development methodology in which an application is specified and designed by describing how its behavior should appear to an outside observer.
• Very smiler to TDD, expanded. Involves all stakeholders.
TDD vs BDD
• http://joshldavis.com/2013/05/27/difference-between-tdd-and-bdd/
Which Unit Test Platforms?
• Jasmine (Javascript Unit Testing Platform) One of the oldest.
Mocha
• Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases. Hosted on GitHub.
Enzyme
• Enzyme is a JavaScript Testing utility for React that makes it easier to assert, manipulate, and traverse your React Components' output.
Jest
• Complete and easy to set-up JavaScript testing solution. Works out of the box for any React project.
• Facebook owns it.
• Not easy, not well documented when we started.
• Current version seems ok.
Our Choice
• Mocha;
• Easy to write,
• well documented
• Good community,
• Can be used with other libraries
• Global State , loacl state moching is easy.
Installing Mocha
• https://mochajs.org/ https://github.com/mochajs/mocha
• $ npm install --global mocha
• $ npm install --save-dev mocha
• Local or global installation ok.
First Test
Sample Project
• Day6/examples/hello-tests
Assertion Libraries
• Mocha allows you to use any assertion library you wish. In the above example, we’re using Node.js’ built-in assert module–but generally, if it throws an Error, it will work! This means you can use libraries such as:• We used chai, but others are ok too.
Asyncronious Test
• Hard thing in unit testing is asynronious function like db / network calls.
• In unit test idea, you run a code and validate the changes.
• So, your code has’nt run when you call it in async.
• You have to wait for it.
Hooks // Before After Each or Oncedescribe('hooks', function() {
before(function() { // runs before all tests in this block });
after(function() { // runs after all tests in this block});
beforeEach(function() { // runs before each test in this block });
afterEach(function() { // runs after each test in this block
}); // test cases});
Sample Project
• Day6/examples/before-after
Asyncronious Test
• In mocha this is easy task.
Promise Tests
Sample Project
• Day6/examples/async-test
ES6 / ES7 in TESTS
• As we already known this is possible with babel.
• npm install babel-core
• Run mocha with babel register code:
• mocha --compilers js:babel-core/register
Sample Project
• Day6/examples/es6-test
Network Calls and Mocking / SPYING
• Mocking is the term for simulating out side data/function calls that will added/called on execution time.
• Ajaxs calls are perfect samples for that.
• Spying is like its name, spy on functions class for their executions. The aim of spying a function is, check if it is called or not, how many calls , which parameters given at call etc.
Sample Project
• Day6/examples/spy-test
Sinon Spy
• http://sinonjs.org/releases/v1.17.7/spies/
Mocha & React
• We use enzyme for react mounting operations.
• Other libraries can be used too
Mocha & React
• Installing
• npm install enzyme
• npm install jsdom
Mocha & React
• var jsdom = require("jsdom").jsdom
• global.document = jsdom('<!doctype html> <html><body></body></html>');
• global.window = global.document.defaultView;
Sample Project
• Day6/examples/react-mocha
Testing Props
• In react components tests, first thing you need to care about is props.
• If your component has props , you have to test each individual.
const wrapper = mount(<Foo bar="baz" />); expect(wrapper.props().bar).to.equal('baz'); wrapper.setProps({ bar: 'foo' }); expect(wrapper.props().bar).to.equal('foo');
Sample Project
• Day6/examples/react-props
Debug Tests
• Very easy, VS code is enough.
• Setup config file
Debug Tests
{"version": "0.2.0","configurations": [
{"name": "Run ES6 Tests","type": "node2","request": "launch","cwd": "${workspaceRoot}","program": "${workspaceRoot}/node_modules/mocha/bin/_mocha","args": [
"./test/*.js","--require", "babel-register","-u", "tdd","--timeout", "999999","--colors"
],"runtimeArgs": [
"--nolazy"],"sourceMaps": true
}]
}
Testing State
• One of other importing thing to test component state.
• Testing is easy
• const wrapper = mount(<Gravatar/>); expect(wrapper.state().email).to.equal('[email protected]');
Testing State
• const wrapper = mount(<Gravatar/>);
• wrapper.setState({ email: '[email protected]' }); wrapper.find('button').simulate('click'); expect(wrapper.state('email')).to.equal('[email protected]'); expect(wrapper.state('src')).to.equal(`http://gravatar.com/avatar/${md5('[email protected]')}?s=200`);
Sample Project
• Day6/examples/react-state
Global State Testing
• In projects, there aren’t only single level components,
• There are containers, pages, sub-modules that combined with multiple components together.
• They also have their global state (redux) that we have learned earlier.
State Mocking
• We have to mock local/global state while unit testing.
• We can create a sample/mock store and give this to redux before testing.
Sample Project
• Day6/examples/react-global-state