[React Testing] Setting up dependencies && Running tests
To write tests for our React code, we need to first install some libraries for running tests and writing assertions. In this lesson we walk through setting up Mocha as our test runner and expect
as our assertion library. We will also set up some React and JSX specific test tools (React Test Utils) to make writing our tests easier.
NOTE: There are many alternatives to Mocha, expect, and the other test tools we use in this course. Although we use these specific tools and libraries, the testing principles apply to all other tools.
package.json:
{ "name": "react-testing", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC", "devDependencies": { "expect": "1.13.4", "mocha": "2.3.4", "react-addons-test-utils": "0.14.5" }, "dependencies": { "react": "0.14.5", "react-dom": "0.14.5" } }
we walk through how to setup our tests and run them. We write a quick empty first test and assertion, so we can run the tests. Using Mocha, we can do this manually each time with the Mocha CLI. We can also automate this using task runner features from tools like Grunt, Gulp, Webpack, or npm scripts. In this course, we will use the common npm test
script setup to run our tests. We will also use the Babel compiler to write our tests with modern JavaScript syntax.
import expect from 'expect'; describe('empty', ()=>{ it('should work', ()=>{ expect(true ).toEqual(true); }); });
packjson.js: Install babel also
{ "name": "react-testing", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "mocha ./src/**/*.spec.js --compilers js:babel-core/register", "test:watch": "npm test -- --watch" }, "author": "", "license": "ISC", "devDependencies": { "babel-core": "6.1.4", "babel-loader": "6.1.0", "babel-preset-es2015": "6.1.4", "babel-preset-react": "6.1.4", "babel-preset-stage-2": "6.1.2", "expect": "1.12.2", "mocha": "2.3.3", "react-addons-test-utils": "0.14.3", }, "dependencies": { "react": "0.14.3", "react-dom": "0.14.3" } }
.babelrc
{ "presets": ["react", "stage-2", "es2015"] }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2015-01-04 [AngularJS] Lazy Loading modules with ui-router and ocLazyLoad
2015-01-04 [AngularJS] Lazy loading Angular modules with ocLazyLoad
2015-01-04 [AngularJS] Consistency between ui-router states and Angular directives