反应unit testing在es6中开玩笑

我在反应世界很新,并试图写简单的朋友列表应用程序。 我用es6风格写了我的朋友商店,并使用babel作为从es5到es6的编译器。

import AppDispatcher from '../dispatcher/app_dispatcher'; import { EventEmitter } from 'events'; import FRIENDS_CONST from '../constants/friends'; const CHANGE_EVENT = 'CHANGE'; let friendsList = []; let add = (name) => { let counter = friendsList.length + 1; let newFriend = { id: counter, name: name }; friendsList.push(newFriend); } let remove = (id) => { let index = friendsList.findIndex(e => e.id == id); delete friendsList[index]; } let FriendsStore = Object.assign({}, EventEmitter.prototype, { getAll: () => { return friendsList; }, emitChange: () => { this.emit(CHANGE_EVENT); }, addChangeListener: (callback) => { this.on(CHANGE_EVENT, callback); }, removeChangeListener: (callback) => { this.removeListener(CHANGE_EVENT, callback); } }); AppDispatcher.register((action) => { switch (action.actionType) { case FRIENDS_CONST.ADD_FRIENDS: add(action.name); FriendsStore.emitChange(); break; case FRIENDS_CONST.REMOVE_FRIENDS: remove(action.id); FriendsStore.emitChange(); break; } }); export default FriendsStore; 

现在我想testing我的商店,并在es6中编写unit testing

 jest.dontMock('../../constants/friends'); jest.dontMock('../friends_store'); describe('FriendsStore', () => { import FRIENDS from '../../constants/friends'; import AppDispatcher from '../../dispatcher/AppDispatcher'; import FriendsStore from '../friends_store'; let FakeAppDispatcher; let FakeFriendsStore; let callback; let addFriends = { actionType: FRIENDS.ADD_FRIENDS, name: 'Many' }; let removeFriend = { actionType: FRIENDS.REMOVE_FRIENDS, id: '3' }; beforeEach(function() { FakeAppDispatcher = AppDispatcher; FakeFriendsStore = FriendsStore; callback = AppDispatcher.register.mock.calls[0][0]; }); it('Should initialize with no friends items', function() { var all = FriendsStore.getAll(); expect(all).toEqual([]); }); }); 

当我用npm test语句执行npm test ,我得到了错误信息:

 > react-starterify@0.0.9 test /Volumes/Developer/reactjs/app5 > echo "Error: no test specified" Error: no test specified 

我究竟做错了什么? 文件结构如下所示: 在这里输入图像描述

要testingES6语法和JSX文件,他们需要被转换为Jest。 Jest有一个configurationvariables,您可以在其中定义一个预处理器(scriptPreprocessor)。 你可以使用babel-jest预处理器:

对package.json进行以下更改:

 { "devDependencies": { "babel-jest": "*", "jest-cli": "*" }, "scripts": { "test": "jest" }, "jest": { "scriptPreprocessor": "<rootDir>/node_modules/babel-jest", "testFileExtensions": ["es6", "js"], "moduleFileExtensions": ["js", "json", "es6"] } } 

并运行:

$ npm install

我按照教程做了:

 npm install --save-dev jest babel-jest babel-preset-es2015 babel-preset-react react-test-renderer 

然后

添加到package.json

  "scripts": { "test": "jest" }, "jest": { "testPathDirs": [ "src/main/resources/web_pages/__tests__" ] }, 

结果:

  PASS src/main/resources/web_pages/__tests__/modules/utils/ValidationUtil.spec.js (5.214s) ✓ ValidateEmail (5ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 6.092s, estimated 7s Ran all test suites.