Search code examples
unit-testingsinonkarma-mocha

How should I write a unit test forJavaScript frontend service that uses promise with Karma, Mocha and Sinon


Trying to test some services I'm writing that interact with a 3rd party API and wondering how to test it efficiently.

I have the next method:

    function getMemberProfile(memberId) {

        //Make sure memberId is defined and that it is a number
        if (!isNaN(memberId)) {
            return Client.authorizedApiRequest('/members/' + memberId).get();
        }
        return Promise.reject(new Error('Proper memberId was not supplied'));
    }

When Client.authorizedApiRequest('/members/' + memberId).get() calls a 3rd party API and returns a Promise that resolves to some Object (i.e. {id:12,name:'John Doe'}).

So, how should I test the getMemberProfile function? I was thinking about mocking out the Client.authorizedApiRequest("some params").get() with sinon but I can't get it working.

Thanks


Solution

  • OK, got it working. First you'll need to install chai. Then, in your spec file:

    beforeEach(function () {
        fakeMember = {
            member: {
                id: 10002,
                first_name: 'John',
                last_name: 'Doe'
            }
        };
    });
    
    it('should get a member\'s profile by memberId', function () {
    
            //mock
            sinon.stub(Client, 'authorizedApiRequest').withArgs('/members/' + fakeMember.member.id).returns({
                get: function () {
                    return Promise.resolve(fakeMember);
                }
            });
    
            return Members.getMemberProfile(fakeMember.member.id).then(function (response) {
                expect(response).to.have.property('member');
                expect(response.member).to.have.property('id', fakeMember.member.id);
                expect(response.member).to.have.property('first_name', fakeMember.member.first_name);
                expect(response.member).to.have.property('last_name', fakeMember.member.last_name);
            });
    
    });