2017-02-18 86 views
4

我正在写我的第一个React测试,并遇到我的beforeEach语句无法正常工作的问题。这是我的测试文件:React&Enzyme:为什么不是beforeEach()工作?

import React from 'react'; 
import { shallow } from 'enzyme'; 
import Home from '../components/Home'; 
import IntroText from '../components/IntroText'; 
import Form from '../components/Form'; 

describe('<Home />',() => { 
    beforeEach(() => { 
    const wrapper = shallow(<Home />); 
    }); 

    it('renders the IntroText component',() => { 
    expect(wrapper.find(IntroText).length).toBe(1); 
    }); 

    it('renders the Form component',() => { 
    expect(wrapper.find(Form).length).toBe(1); 
    }); 
}); 

下面是相关的部分我package.json

"devDependencies": { 
    "babel-jest": "^18.0.0", 
    "babel-preset-es2015": "^6.22.0", 
    "babel-preset-react": "^6.23.0", 
    "jest": "^18.1.0", 
    "react-scripts": "0.9.0", 
    "react-test-renderer": "^15.4.2" 
}, 
"dependencies": { 
    "enzyme": "^2.7.1", 
    "jest-enzyme": "^2.1.2", 
    "react": "^15.4.2", 
    "react-addons-test-utils": "^15.4.2", 
    "react-dom": "^15.4.2", 
    "react-router": "^3.0.2" 
}, 
"scripts": { 
    "start": "react-scripts start", 
    "build": "react-scripts build", 
    "test": "react-scripts test --env=jsdom", 
    "eject": "react-scripts eject" 
} 

当测试运行我得到这个错误:

ReferenceError: wrapper is not defined 

我缺少什么?

回答

11

你所定义的范围beforeEach内包装常量,外移动这样的:

import React from 'react'; 
import { shallow } from 'enzyme'; 
import Home from '../components/Home'; 
import IntroText from '../components/IntroText'; 
import Form from '../components/Form'; 

describe('<Home />',() => { 
    let wrapper; 
    beforeEach(() => { 
    wrapper = shallow(<Home />); 
    }); 

    it('renders the IntroText component',() => { 
    expect(wrapper.find(IntroText).length).toBe(1); 
    }); 

    it('renders the Form component',() => { 
    expect(wrapper.find(Form).length).toBe(1); 
    }); 
}); 

这种方式,您将有机会在it适适用范围里面来包装。

常量是块范围的,就像使用让 语句定义的变量。常量的值不能通过 重新赋值而更改,并且不能重新声明。

既然你想将变量分配beforeEach范围内,并用它的it范围内,你必须声明变量在一个共同的范围内,其中,在这种情况下是describe范围。

补充:

另一种可能的方式来解决这个问题是使用this关键字(我喜欢)。

import React from 'react'; 
import { shallow } from 'enzyme'; 
import Home from '../components/Home'; 
import IntroText from '../components/IntroText'; 
import Form from '../components/Form'; 

describe('<Home />', function() { 
    beforeEach(function() { 
    this.wrapper = shallow(<Home />); 
    }); 

    it('renders the IntroText component', function() { 
    expect(this.wrapper.find(IntroText).length).toBe(1); 
    }); 

    it('renders the Form component', function() { 
    expect(this.wrapper.find(Form).length).toBe(1); 
    }); 
}); 
+0

谢谢。你能解释为什么这样吗? – jslutzky

+0

已更新,希望能使它更清晰一些。 – Canastro

+0

非常感谢! – jslutzky