2017-02-18 34 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