我试图为我现有的项目创建测试文件
https://github.com/facebookincubator/create-react-app
但是当我运行npm测试时我得到了这个错误
- FAIL src/__tests__/movie_single/MovieSingle-test.js
- ● Test suite Failed to run
- matchMedia not present,legacy browsers require a polyfill
- at Object.MediaQueryDispatch (node_modules/enquire.js/dist/enquire.js:226:19)
- at node_modules/enquire.js/dist/enquire.js:291:9
- at Object.<anonymous>.i (node_modules/enquire.js/dist/enquire.js:11:20)
- at Object.<anonymous> (node_modules/enquire.js/dist/enquire.js:21:2)
- at Object.<anonymous> (node_modules/react-responsive-mixin/index.js:2:28)
- at Object.<anonymous> (node_modules/react-slick/lib/slider.js:19:29)
- at Object.<anonymous> (node_modules/react-slick/lib/index.js:3:18)
- at Object.<anonymous> (src/components/movie_single/MovieDetailsBox.js:4:45)
- at Object.<anonymous> (src/components/movie_single/MovieSingle.js:3:50)
- at Object.<anonymous> (src/__tests__/movie_single/MovieSingle-test.js:3:46)
- at process._tickCallback (internal/process/next_tick.js:103:7)
- Test Suites: 1 Failed,1 total
- Tests: 0 total
- Snapshots: 0 total
- Time: 2.642s
- Ran all test suites matching "a".
所以这是我的package.json
- {
- "name": "xxx","version": "0.1.0","private": true,"devDependencies": {
- "autoprefixer-stylus": "0.10.0","concurrently": "3.0.0","react-scripts": "0.6.1","stylus": "0.54.5"
- },"scripts": {
- "start": "react-scripts start","watch": "concurrently --names 'webpack,stylus' --prefix name 'npm run start' 'npm run styles:watch'","build": "react-scripts build","test": "react-scripts test --env=jsdom","eject": "react-scripts eject",}
- }
这是我的MovieSingle-test.js
- import React from 'react';
- import ReactDOM from 'react-dom';
- import MoviesSingle from '../../components/movie_single/MovieSingle';
- it('renders without crashing',() => {
- const div = document.createElement('div');
- ReactDOM.render(<MoviesSingle />,div);
- });
那么我该如何解决这个问题并至少让常见的反应组件测试通过?
谢谢!
将src / setupTests.js添加到项目中(将在运行测试之前执行):
- /**
- * fix: `matchMedia` not present,legacy browsers require a polyfill
- */
- global.matchMedia = global.matchMedia || function() {
- return {
- matches : false,addListener : function() {},removeListener: function() {}
- }
- }