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 asusers
is not available directly, its a sub-object ofstore
- 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
- [Vuejs]-VueJs components are not showing using the Vue router
- [Vuejs]-How do I handle url data between domain and hashtag with Vue Router?
Source:stackexchange.com