Load local JSON into Jasmine/Karma Unit Test in AngularJS

落爺英雄遲暮 提交于 2019-12-02 04:42:24

You can do it like this:

var LoginService, $controller;

var formFetcherService = {
    updateCachedForms: jasmine.createSpy('sessionData');
}

var response = {
    data: {
        user_id: 4,
        forms: 'some'
    }
}

beforeEach(module(function($provide) {
    $provide.value('LoginService', {
        login: function(url, username, password, successCallback, errorCallback) {
            successCallback(response);
        }
    });

    $provide.value('FormFetcherService', formFetcherService);
}))

beforeEach(inject(function(_$controller_) {
    $controller = _$controller_;
});

it('should create sessionData', function() {
    var controller = $controller('HomeController');
    controller.submitLogin();
    expect(formFetcherService.updateCachedForms).toHaveBeenCalledWith(response.user_id, response.form_uri);
});

@dean-sherwin Though this might not actually answer the question, I'd like to share the piece of code that I've been using to load the json from a file for jasmine testing because:

  • not always do you want to keep the huge json data in one test spec
  • helps in sharing that json data across multiple specs if need be

spyOn(SomeClass, 'someMethod').and.returnValue( $.ajax({ url: "somefolder/anotherfolder/theJSONFile.json", async: false, dataType: "json" }).then(function(data) { return data }) );

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!