준비물


import * as React from 'react';
import { configure, shallow, mount } from 'enzyme';
import * as Adapter from 'enzyme-adapter-react-16';
import * as chai from 'chai';
import { expect, assert } from 'chai';
import * as sinon from 'sinon';


file 읽어와서 미리 보기 뿌려주는 과정이 비동기였는데 생각을 못해서 하루종일 해맸던 과정이다.


describe('ImageInputComponent test', () => {

var stub = sinon.stub();
var callback;
const onUploadFileLatency = 100;

it(`when file change, onUploadFile run (latency time about ${onUploadFileLatency}ms)`, done => {
const onUploadFile = async function (uploadFile: UploadFile) {
}

var spy = sinon.spy(onUploadFile);

const Wrapper = shallow(<ImageInputComponent onUploadFile={spy} />);

const fileInput = Wrapper.find('input[type="file"]');

fileInput.simulate('change', { target: { files: [
new Blob(['aaa'])
]}});
setTimeout( () => {
expect(spy.calledOnce);
done();
spy.restore();
}, onUploadFileLatency);
});
});


setTimeout이 없으면 onUploadFile이 실행되기전에 expect가 먼저 실행되서 spy.calledOncer가 false로 나온다.

onUploadFileLatency는 0 을 줘도 쾌적한 환경에서는 잘 된다. 


method 설명

sinon.spy(fn?: Function)


argument는 없어도 되고 입력 받은 함수를 새로운 프록시로 감싼다.

spy.restore() 는 오리지날 함수로 복구해주는 함수다.


shallow는 얕은 렌더링 이라고 생각하면 된다.

자식 component는 렌더링 하지 않는다. html들은 관련 없다.

자식 component를 렌더링 하고 싶다면

Wrapper.dive()를 사용하면 된다.

자식 dom은 find(selector)를 사용해 찾을 수 있다. css selector형식을 사용한다.


dom이벤트 발생은 simulate로 발생 시킬 수 있다. 이벤트 이름은 javascript native와 같고 change같은 경우 두번째 인자로 값을 전달 할 수 있다.

event타입의 객체이다. e.target.value같은 걸로 많이 사용해봤을 것이다. 같은 구조이다.


expect는 chai를 이용했고 spy객체에 calledOnce는 한번 호출 됐는지 기록되는 변수다.

(spy변수 참조: http://sinonjs.org/releases/v6.1.3/spies/ )


마지막으로 done()은 비동기함수 검사가 끝나다는 신호다.

비동기로 실행되는 assertion은 done()이 실행되지 않으면 결과 반영을 하지 않는다.


+ Recent posts