dimanche 10 juillet 2016

Debugging infinite digest for $rootScope.$apply in unit tests

I have a simple test for my UserService that calls my ApiService. I'm using a third party API SDK so I can't use $httpBackend directly, but I've set it up so that at least for now empty data is returned from the API:

// ApiService mock
beforeEach(module($provide =>
    $provide.factory("ApiService", $q => ({
        request: () => $q.resolve({data: {}}),
    }))
));

// Test
describe("registerUser", () => {
    it("registers user", () => {
        const registerId = "registerId";
        $window.SDK = {credentials: {registerId}};

        UserService.registerUser("socialId", "email");
        $rootScope.$apply();

        expect(UserService.registerId).to.equal(registerId);
    });
});

// Implementation
function UserService(ApiService, $window) {
    let service = {};
    service.registerUser = (socialId, email) => {
        return ApiService.request("registerUser", {socialId, email}).then(response => {
            service.registerId = $window.SDK.credentials.registerId;
        });
    };
    return service;
}

Essentially the UserService calls ApiService which calls the SDK. This sets the internal registerId which gets set on UserService.

I am using $rootScope.$apply in order to resolve the promise. In fact, if I do call it, I confirm that registerId is appropriately set. However, I get [$rootScope:infdig] 10 $digest() iterations reached. Aborting!

If I don't use $rootScope.$apply the promise is never resolved and registerId never gets set.

Is there any other way to resolve the promise or mock this API? In general, how can I properly debug what would be causing the infinite digest cycle from this $rootScope.$apply? It doesn't seem to be calling registerUser in a loop.

Aucun commentaire:

Enregistrer un commentaire