lundi 20 novembre 2017

Writing JEST unit test for a simple function

Basically this is my react code

    getDetails: function () {
        var apiUrl = ConfigStore.get('api')
        request
            .get(apiUrl)
            .set('X-Auth-Token', AuthStore.jwt)
            .set('Accept', 'application/json')
            .end(function (err, response) {
                if (!err) {
                    if(response.text.indexOf("string") > -1){
                        this.dispatch('COMMAND1', response);
                    }
                    else {
                        this.dispatch('COMMAND2', response.body.options);
                    }
                }
                else {
                    this.dispatch('COMMAND3', response && response.body);
                }
            }.bind(this));
    }

I've written an unit test for the above function of COMMAND1

    it('Getting Latest Details', () => {
    let eventSpy = sinon.spy();
        require('superagent').__setMockResponse({
            body: {               
                firstName: 'blah',
                lastName: 'm ',
                username: 'blah',
                text: {
                    text : jest.fn()
                }               
            }
        }); 
        let dispatchListener = AppDispatcher.register((payload) => {
            if (payload.action.type === 'COMMAND1') {
                eventSpy(payload.action.payload);               
            }
        });     

        AuthStore.loggedIn = jest.genMockFunction().mockReturnValue(true);
        AuthStore.getToken = jest.genMockFunction().mockReturnValue('545r5e45er4e5r.erereere');
        MedsAlertsActions.getDetails();
        expect(eventSpy.called).toBe(true);
        dispatch('COMMAND1', data);
        AppDispatcher.unregister(dispatchListener);
});   

When i run

npm test myfile.test

I'm getting

TypeError: Cannot read property 'indexOf' of undefined

  1. So how do i put the indexOf the response in my body? How to resolve the type error
  2. How to write test cases for command2 and command3 as well.

Aucun commentaire:

Enregistrer un commentaire