[Web] How to Test React and MobX with Jest
Introduction
If you’re developing React applications, then you know that the React community has been bursting with new ideas and tools over the last year. When investigating any new technology to incorporate into a stack, we should consider if it either makes the workflow much easier, or solves a key problem. MobX and Enzyme are 2 new libraries in the React world that fit the bill. This sample todo application is incredibly easy to build with React and MobX, and in this article we’ll cover unit and UI/functional testing for React and MobX with Enzyme.
Code Smell in React
There’s no shortage of ways to build applications with React, but one thing is for sure — React shines the brightest when it is used as a reactive view layer sitting on top of the state of your application. If you use it for more than that, e.g. the UI is responsible for determining when and how to load data or the UI stores certain aspects of state, this can quickly lead to code smell.
In order to keep our React projects from growing messy, we need store the application state completely outside of the UI. This will not only make our application more stable, but it will also make testing extremely simple, as we can test the UI and the state separately.
Enter MobX
While frameworks and patterns like Flux, Redux and Relay give you a powerful way to manage the state of your application outside of the React view layer, they are complicated to set up, and it can take a while to make simple changes. One of the big reasons that MobX is quickly growing in popularity is the fact that it is very simple, which is nearly as simple as coding an object literal . That means you get a tremendous developer experience without sacrificing application stability.
What is Enzyme?
Enzyme will be our testing tool of choice, since it will allow us to test React components with jQuery-like syntax. This means functional and integration-style tests will be easy to write.
Accessing the Code:
- You can find the code for the simple todo application on GitHub: learncodeacademy/react-js-tutorials,
- The only requirement is Node.js version 4 or higher,
- To get it up and running, type
npm install && npm start, and - Visit the application on
localhost:8080.
Now, let’s get to testing this application.
Installing Enzyme and Jest
While Mocha works great with Enzyme, Jest is a little bit simpler to set up. Our 3 testing dependencies will be: jest for testing, babel-jest for transpiling our ES6, and enzyme for our functional React tests. Let’s clone the repository, then run npm install and also install those dependencies.
git clone git@github.com:learncodeacademy/react-js-tutorials.git
cd react-js-tutorials/6-mobx-react
npm install
npm install --save-dev enzyme jest babel-jest
With these packages installed, Jest is fully configured out of the box. Babel will still work great as long as Babel is configured with a .babelrc file. Some people configure Babel in webpack.config.js, if that’s you, then you’ll need to move it to the .babelrc file so Jest and Webpack can both use the config.
We can now run jest and notice that no tests are found:
$ jest
Using Jest CLI v14.1.0, jasmine2, babel-jest
NO TESTS FOUND. 5 files checked.
testPathDirs: /Users/cmn/Code/sandbox/react-mobx - 5 matches
testRegex: __tests__/.*.js$ - 0 matches
testPathIgnorePatterns: /node_modules/ - 5 matches
Unit Testing with MobX
Since MobX classes behave like object literals, testing is incredibly simple. Let’s begin by unit testing our TodoList store. Jest will run anything in the __tests__ directory by default, so let’s run these 2 commands to make the directory as well as our first test file.
mkdir __tests__
touch __tests__/TodoStore.test.js
Jasmine is the default runner for Jest, so we have access to describe, it, and expect without configuring anything. This means that we can get straight to writing our first test.
import { TodoStore } from "../src/js/TodoStore"
describe("TodoStore", () => {
it("creates new todos", () => {
const store = new TodoStore
store.createTodo("todo1")
store.createTodo("todo2")
expect(store.todos.length).toBe(2)
expect(store.todos[0].value).toBe("todo1")
expect(store.todos[1].value).toBe("todo2")
})
We created a new TodoStore, did some actions and observed the result just as if it were an object literal. The biggest advantage of MobX is its simplicity. Any changes we made would have been passed onto any observers as well. It’s important to note that we imported the store constructor { TodoStore } and not the default export, which is an instantiated store. This allows our next test to instantiate its own fresh store as well:
it("clears checked todos", () => {
const store = new TodoStore
store.createTodo("todo1")
store.createTodo("todo2")
store.createTodo("todo3")
store.todos[1].complete = true;
store.todos[2].complete = true;
store.clearComplete()
expect(store.todos.length).toBe(1)
expect(store.todos[0].value).toBe("todo1")
})
With unit testing in place, let’s use Enzyme to do some unit tests against our UI layer:
Unit Testing with React and Enzyme
Let’s being by making the file:
touch __tests__/TodoList.unit.test.js
Again, since MobX stores act just like object literals, we can test our React component by injecting it with any object literal to simulate a store state. We can use a single beforeEach to provide this state to all tests:
import { shallow } from 'enzyme'
import React from "react"
import TodoList from "../src/js/TodoList"
describe("TodoList", function() {
//don't use an arrow function...preserve the value of "this"
beforeEach(function() {
this.store = {
filteredTodos: [
{value: "todo1", id: 111, complete: false},
{value: "todo2", id: 222, complete: false},
{value: "todo3", id: 333, complete: false},
],
filter: "test",
createTodo: (val) => {
this.createTodoCalled = true
this.todoValue = val
},
}
})
//tests will go here and receive this.store
})
Notice how we do not use an ES6 arrow function for the beforeEach? We want to make sure that the value of this remains the same or this.store will not get passed on to our tests. When using context for tests, it’s a good idea to stop using arrow functions. However, we want to use an arrow function on our createTodo function, so we can set this.todoClicked and this.todoValue on the parent context when it gets called.
Now, adding a test is straightforward:
//don't use an arrow function, preserve the value of "this"
it("renders filtered todos", function() {
const wrapper = shallow(<TodoList store={this.store} />) expect(wrapper.find("li span").at(0).text()).toBe("todo1")
expect(wrapper.find("li span").at(1).text()).toBe("todo2")
expect(wrapper.find("li span").at(2).text()).toBe("todo3")
})
We use Enzyme to create a wrapper for our store-injected-component, then we can ensure that all 3 todos printed correctly. Now, let’s add some tests that simulate user interaction on the component:
it("calls createTodo on enter", function() {
const wrapper = shallow(<TodoList store={this.store} />)
wrapper.find("input.new").at(0)
.simulate("keypress", {which: 13, target: {value: 'newTodo'}})
expect(this.createTodoCalled).toBe(true)
expect(this.todoValue).toBe("newTodo")
})
it("updates store filter", function() {
const wrapper = shallow(<TodoList store={this.store} />)
wrapper.find("input.filter").at(0)
.simulate('change', {target: {value: 'filter'}})
expect(this.store.filter).toBe("filter")
})
Enzyme allows us to easily simulate real JS events. The first argument of simulate is the event type, and the 2nd argument is the event object. Now, we have verified that the component calls createTodo when todos are created and also updates the filter when changed.
Integration Tests
Every now and then, you may find it useful to test that components work together the way they should. If you want to do this with React and MobX, you should simply replace the mock store with a real MobX store. Create TodoList.functional.test.js and add this:
import { shallow } from 'enzyme'
import React from "react"
import TodoList from "../src/js/TodoList"
import { TodoStore } from "../src/js/TodoStore"
describe("TodoList.functional", () => {
it("filters todos", () => {
const store = new TodoStore
store.createTodo("todo1")
store.createTodo("todo2")
store.createTodo("todo3")
store.filter = "2"
const wrapper = shallow(<TodoList store={store} />)
expect(wrapper.find("li").length).toBe(1)
expect(wrapper.find("li span").at(0).text()).toBe("todo2")
})
})
We are able to verify that the component behaves correctly with an actual MobX store as well. We can also verify that user interaction modifies the store appropriately:
it("clears completed todos when 'clear completed' is clicked", () => {
const store = new TodoStore
store.createTodo("todo1")
store.createTodo("todo2")
store.createTodo("todo3")
store.todos[0].complete = true
store.todos[1].complete = true
const wrapper = shallow(<TodoList store={store} />)
wrapper.find("a").simulate("click")
expect(wrapper.find("li").length).toBe(1)
expect(wrapper.find("li span").at(0).text()).toBe("todo3")
expect(store.todos.length).toBe(1)
})
Notice our expect at the bottom, we can verify that both the UI and the store changed appropriately when the “clear completed” link is clicked.
[Web] How to Test React and MobX with Jest的更多相关文章
- [Web 前端] 如何构建React+Mobx+Superagent的完整框架
ReactJS并不像angular一样是一个完整的前端框架,严格的说它只是一个UI框架,负责UI页面的展示,如果用通用的框架MVC来说,ReactJs只负责View了,而Angular则是一个完整的前 ...
- Facebook的Web开发三板斧:React.js、Relay和GraphQL
2015-02-26 孙镜涛 InfoQ Eric Florenzano最近在自己的博客上发表了一篇题为<Facebook教我们如何构建网站>的文章,他认为软件开发有些时候需要比较大的跨 ...
- React使用Mobx管理数据
React 和 Vue一样都属于单向数据流,为了更好的进行状态和数据管理官方和第三方也有配套的Redux等插件,本文介绍一个个人觉得更易用使用的组件 Mobx 核心概念 MobX 处理你的应用程序状态 ...
- react使用mobx
mobx api 使用装饰器语法 mobx数据转化为js数据 安装 yarn add mobx mobx-react yarn add babel-preset-mobx --dev "pr ...
- react+react-router+mobx+element打造管理后台系统---react-amdin-element
react-admin-element,一款基于react的后台管理系统. 那么我们和其他的后台管理系统有什么区别呢? demo地址:点我进入demo演示 github地址:点我进入github 1. ...
- 【Web技术】401- 在 React 中使用 Shadow DOM
本文作者:houfeng 1. Shadow DOM 是什么 Shadow DOM 是什么?我们先来打开 Chrome 的 DevTool,并在 'Settings -> Preferences ...
- [Web 前端] 如何在React中做Ajax 请求?
cp from : https://segmentfault.com/a/1190000007564792 如何在React中做Ajax 请求? 首先:React本身没有独有的获取数据的方式.实际上, ...
- 【前端单元测试入门05】react的单元测试之jest
jest jest是facebook推出的一款测试框架,集成了前面所讲的Mocha和chai,jsdom,sinon等功能. 安装 npm install --save-dev jest npm in ...
- 从零配置webpack(react+less+typescript+mobx)
本文目标 从零搭建出一套支持react+less+typescript+mobx的webpack配置 最简化webpack配置 首页要初始化yarn和安装webpack的依赖 yarn init -y ...
随机推荐
- 从零搭建一个简单的webpack环境
1.npm Init 2.创建webpack.config.js文件,并配置入口和出口 3.Package.json的script中配置命令对应的操作 .安装webpack-dev-server 模块 ...
- 关于ionic2在IOS上点击延迟的问题
正常的点击事件, 不知道 为什么 ,在IOS上明显会延迟几百毫秒.. 加上tappable属性就可以解决了 <div tappable (click)="doClick()" ...
- Python如何去实际提高工作的效率?也许这个会有用!
4月初,班主任的某次周会议上,华华关切的问了一下:最近班主任们有什么难题吗?就是花费了你们大部分时间的工作!我们Python天团可以帮你们解决问题. 班主任大主管星星说:有.目前有一个大难题.我们每天 ...
- Integrated SOA Gateway 不是当前用户的有效责任。请联系您的系统管理员。
问题:给用户新增职责集成SOA网关,点击路径进入时出现报错:"Integrated SOA Gateway 不是当前用户的有效责任.请联系您的系统管理员." 解决:功能管理员职责, ...
- Web架构之路:MongoDB集群及高可用实践
MongoDB集群有副本集及主从复制两种模式,不过主从模式在MongoDB 3.6已经彻底废弃,今天主要探讨副本集的搭建和使用,以及分片. 副本集介绍 副本集(Replica Set)即副本的集合,在 ...
- 【漏洞复现】Apache Solr via Velocity template远程代码执行
0x01 概述 Solr简介 Apache Solr 是一个开源的企业级搜索服务器.Solr 使用 Java 语言开发,主要基于 HTTP 和 Apache Lucene 实现.Apache Solr ...
- Mac 设置redis开机启动
1.创建一个plist文件 首先我们需要在/Library/LaunchDaemons目录下创建一个plist文件,使用如下命令: 复制代码代码如下: sudo vim /Library/Launch ...
- Laravel 实现前后台用户分离登录
在很多时候,我们需要前台和后台进行不同的登录操作,以限制用户权限,现在用 Laravel 实现这个需求. 前戏 一.获取 Laravel 这个在文档中都有说明的,也比较简单,可以使用 composer ...
- 自定义View(四),onMeasure
转自:http://blog.csdn.net/a396901990/article/details/36475213 简介: 在自定义view的时候,其实很简单,只需要知道3步骤: 1.测量--on ...
- 【Git】Git如何合并某一次commit的内容到指定分支
一.我是在什么场景下会用到该Git操作 当某同事,将开发分支dev2合并到开发分支dev1时(两个不同的功能,不能合并),其他同事不知情的情况下,继续在dev1上开发并提交了代码. 后面发现了该合并, ...