Mocking an angular service in Protractor
Asked Answered
M

1

2

I'm trying to use Protractor's addMockModule to insert mock data in my end-2-end test.

My test is supposed to go to a web site, find a button by css-class and click it. The button click calls the function dostuff() in MyService, which fetches data from the backend.

My code so far:

describe('should display validation error', function () {

it('should work', function () {
    browser.get('http://my.url');

    browser.addMockModule('MyService', function () {
            // Fake Service Implementation returning a promise
            angular.module('MyService', [])
            .value({
                dostuff: function () {
                    return {
                        then: function (callback) {
                            var data = { "foo": "bar" };
                            return callback(data);
                        }
                    };
                }
            });
    });

    var button = element(by.css('.btn-primary'));
    button.click();
    browser.sleep(5000);
});
});

The test is accessing the web site and clicking the button. The problem is that real data from the database is displayed, not the mock data. I followed several threads, like this one: How to mock angular.module('myModule', []).value() in Jasmine/Protractor

However, it seems like the function protractor.getInstance() is deprecated.

Anyone got this working?

Mildew answered 27/11, 2015 at 11:58 Comment(1)
Concerning "protractor.getInstance" have a look here: #25496879Doit
H
2

Take a look at the unit test for addMockModule(). Try to add the addMockModule statement before you call browser.get()

https://github.com/angular/protractor/blob/673d416b7ef5abd0953da940cfa8cf2a59650df4/spec/basic/mockmodule_spec.js

Hexagram answered 27/11, 2015 at 15:41 Comment(2)
Hmm, nope, that didn't help. I'm still getting data from the database instead of the mock data. Anyone else have any ideas?Mildew
I am getting this message in my Selenium console window. Is this an indication that Protractor is unable to access the angular app? <br/> if (!angular.element(el).injector()) { throw new Error('root element (' + rootSelector + ') has no injector.' + ' this may mean it is not inside ng-app.'); } angular.element(el).injector().get('$browser'). notifyWhenNoOutstandingRequests(callback); } } catch (err) { callback(err.message);Mildew

© 2022 - 2024 — McMap. All rights reserved.