2016-09-04 7 views
2

Jest와 ES6 클래스를 사용하여 React store를 테스트하려고합니다. 나는 모든 테스트를하기 전에 테스트 된 매장을 "재설정"하거나 신선한 인스턴스를 얻는 방법을 궁금해하고있었습니다.ES6에 Jest와 Flux Store를 테스트하십시오.

내 저장소가 포함

import BaseStore from './BaseStore'; 
import { MIDI_PLUGIN_LOADED } from '../constants/MidiConstants'; 


class MidiStore extends BaseStore { 

    constructor() { 
    super(); 
    this.subscribe(() => this._registerToActions.bind(this)); 
    this._midiPlayer = null; 
    } 

    _registerToActions(action) { 
    switch (action.actionType) { 
     case MIDI_PLUGIN_LOADED: 
     this._midiPlayer = action.player; 
     this.emitChange(); 
     break; 
    } 
    } 

    get midiPlayer() { 
    return this._midiPlayer; 
    } 
} 

export default new MidiStore(); 

내 농담 테스트 코드 :

import { MIDI_PLUGIN_LOADED } from '../../constants/MidiConstants'; 
import AppDispatcher from '../../dispatchers/AppDispatcher'; 
import MidiStore from '../MidiStore'; 

describe('MidiStore',() => { 

    var actionMidiPluginLoaded = { 
    actionType: MIDI_PLUGIN_LOADED, 
    player: true 
    }; 

    it('stores global midi plugin',() => { 
    AppDispatcher.dispatch(actionMidiPluginLoaded); 
    let { 
     midiPlayer 
    } = MidiStore; 

    expect(midiPlayer).toBe(true); 
    }); 

    // fails cause midiPlayer = true 
    it('should initialize with no player',() => { 
    let { 
     midiPlayer 
    } = MidiStore; 

    expect(midiPlayer).toBeNull(); 
    }); 

}); 

문제는 MidiStore이 첫 번째 후 resetted되지 않기 때문에 두 번째 "을"-statement이 실패한다는 것입니다 운영.

두 개의 "it"구문을 전환하면 두 가지 테스트가 모두 통과된다는 것을 알고 있지만 이는 실제 해결책이 아닙니다.

ES5 Jest에서는 beforeEachvar MidiStore = require('../MidiStore);을 호출하여 모든 실행에서 새 인스턴스를 얻을 수있었습니다. ES6에서 어떻게이 작업을 수행 할 수 있습니까?

답변

1

나는이 문제를 직접 해결할 수있었습니다. joths beforeEach 콜백에서 "old"require을 사용하면 각 테스트 함수에 대해 새 인스턴스를 가져올 수 있습니다. 난 jest.resetModules(); 모듈로 재설정 및 디스패처 저장하고 등록 된 콜백의 새로운 인스턴스를 잡아 beforeEach 호출

import { MIDI_PLUGIN_LOADED } from '../../constants/MidiConstants'; 

jest.mock('../../dispatchers/AppDispatcher'); 

describe('MidiStore',() => { 

    var AppDispatcher; 
    var MidiStore; 
    var callback; 

    var actionMidiPluginLoaded = { 
    actionType: MIDI_PLUGIN_LOADED, 
    player: true 
    }; 

    beforeEach(() => { 
    jest.resetModules(); 
    AppDispatcher = require('../../dispatchers/AppDispatcher').default; 
    MidiStore = require('../MidiStore').default; 
    callback = AppDispatcher.register.mock.calls[0][0]; 
    }); 

    it('registers a callback with the dispatcher',() => { 
    expect(AppDispatcher.register.mock.calls.length).toBe(1); 
    }); 

    it('stores global midi plugin',() => { 
    callback(actionMidiPluginLoaded); 
    expect(MidiStore.midiPlayer).toBe(true); 
    }); 

    it('should initialize with no player',() => { 
    expect(MidiStore.midiPlayer).toBeNull(); 
    }); 

}); 

. 등록 된 콜백은 이제 jest에 의해 조롱 된 디스패처에서 검색됩니다. 모의 함수 (다른 테스트에서) 구현을 위해, 나는 https://facebook.github.io/jest/docs/api.html#mockfn-mockimplementation-fn

을 참조했다.
관련 문제