Mocking an angular service in Protractor

2019-05-25 18:27发布

问题:

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?

回答1:

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