0

I am writing unit tests for my website at work and I cant seem to figure out how to test an api call.

Lets say I want to test an api call in one of my Vue components

  api.ajax("users")
.done((response) => {
  stores.usersStore.init(response)
})

usersStore.js

 let usersStore = {

  store: {
    users: []
  },

  get() {
    return this.store
  },

  set(key, value) {
    if (key) {
      this.users[key] = value
    } else {
      console.error("Key required")
    }
  },

  init(initObject) {
    this.store.users = initObject
  }


}

export default usersStore;

So the api call basically just initializes the array of users. How do I test something like this in jasmine? I tried spies, and mocking.

Any inputs would be greatly appreciated!

Edit --> The test I am attempting to write

  describe(" Tests", function() {

  var us;

    beforeEach(function() {

      us = new usersStore()
       us.store.users.push("Anand Dharne")
    });

    describe("when retrieved by name", function() {
      var u;

      beforeEach(function(done) {
        u = us.init(response, {
          success: function () {
            done();
          }
        });
      });

      it("api call", function() {
        expect(u.store.users).toEqual("Anand Dharne");
      });
    });
  });
Winter Soldier
  • 2,607
  • 3
  • 14
  • 18

1 Answers1

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
Winter Soldier
  • 2,607
  • 3
  • 14
  • 18