[Vuejs]-Unit tesing an api call using jasmine

0👍

  • You may spy on the ajax object.
  • Since I’m not completely familiar with vue.js I’d like to share a simple implementation using plain javascript, jQuery & jasmine . See it in action

    var usersStore = {
     store: {
        users: []
      },
      get: function() {
        return this.store;
      },
      set: function(key, value) {
        if (key) {
          this.store[key] = value;
        } else {
          console.error("Key required");
        }
      },
      init: function(initObject) {
        this.store.users = initObject;
      }
    };
    
    var api = {
      serviceCall: () => {
        $.ajax('').done((data) => {
          usersStore.init(data);
        });
      }
    };
    
    describe('test api call', () => {
      it('ajax success', () => {
        expect(true).toBe(true);
        var userObj = [{
          'name': 'StackOverflow'
        }];
        spyOn($, 'ajax').and.callFake((e) => {
          return $.Deferred().resolve(userObj).promise();
        });
        api.serviceCall();
        expect(usersStore.get().users[0].name).toEqual('StackOverflow');
      });
    });
    

Points to Note:

  • The code this.users[key] = value from your set method may not be valid as users is not available directly, its a sub-object of store
  • You need to use a custom $Deferred() object that returns a promise which could either be resolved/rejected
  • I’ve not used arrow functions for the methods of object as they need a this reference. More about arrow function here
  • Also to explore other options of mocking ajax calls, I’d suggest you to start here

Leave a comment