Malik
Malik

Reputation: 3680

Mocking $window object inside Angular .config

I am getting following error while trying to run karma tests spec in my app.

        Error: [$injector:modulerr] Failed to instantiate module adf.widget.tabularWidget due to:
        Error: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
            at Error (native)
            at C:/Users/dell%20pc/Documents/Work/Client/widgets/TabularWidget/src/ta
bularWidget.js:22:43
            at Object.invoke (C:/Users/dell%20pc/Documents/Work/Client/bower_compone...

the problem here is that , when i run the tests , it fails to mock the window property . following is the file where this issue occurs ..

'use strict';
(function (windows, angular, $, _) {

    angular.module('adf.widget.tabularWidget')
        .config(function (dashboardProvider) {

            //more code

            //issue line
            var widgetDefsApiUrl = window.atob(window.api) +
                "Widget/definitions?access_token=" + window.atob(window.acstkn);

        });

})(window, angular, $, _);

But when i just comment out that line every test cases runs okay without any issue . So if i can mock the widgetDefsApiUrl somehow and inject it to my test cases my problem would be solved . But i am not sure how to do it . Can anyone please point me in the right direction ?

EDIT : I have isolated the problem . The problem is that window.api is undefined here hence the window.atob() gives the error . How would i overcome this problem ?

Upvotes: 1

Views: 1208

Answers (2)

Suneet Bansal
Suneet Bansal

Reputation: 2702

You can directly get window object and attach properties and methods onto it.

beforeEach(function() {
        window.api = function() {};
        window.atob = function() {};
)};

Upvotes: 3

Malik
Malik

Reputation: 3680

Found the solution . just need to mock the window object inside a beforeEach block .

beforeEach(function() {
        var window = {};
        window.api = "windowsapitoken";
        window.acstkn = "windowsacsapitoken";

)};

Upvotes: 2

Related Questions