2017-02-18 3 views
4

첫 번째 React 테스트를 작성하고 있는데 내 beforeEach 문이 작동하지 않는 문제가 있습니다. 여기 내 테스트 파일입니다 :반응 및 효소 : 왜 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 범위 내에서 래퍼를 const 정의하고, 다음과 같이 외부로 이동 :

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의 범위 내에서 래퍼에 액세스 할 수 있습니다이 방법을.

상수는 let 문을 사용하여 정의 된 변수와 마찬가지로 블록 범위입니다. 상수의 값은 재 할당을 통해 변경할 수 없으며 다시 선언 할 수 없습니다. 당신이 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