7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AngularJSでPromiseを返す関数をモック化してテストする

Posted at

Promiseを返す関数をモック化してテストするサンプルです。
Promiseがresolveやrejectされた後の処理はscope.$digest()が呼ばれないと実行されないため、
テストコード内のどこかのタイミングでscope.$digest()を呼んでやる必要があります。

controller
angular.module("myApp", []).controller("hogeController", function ($scope, hogeService) {
    $scope.hoge = "";
    hogeService.deferredHoge().then(function (x) {
        $scope.hoge = x;
    });
});
testcode
describe("Promise test sample", function () {

    var $rootScope;
    var $q;
    var $controller;

    beforeEach(function () {
        module("myApp")
    });

    beforeEach(inject(function (_$rootScope_, _$q_, _$controller_) {
        $rootScope = _$rootScope_;
        $q = _$q_;
        $controller = _$controller_;
    }));

    it("controller初期化時にdeferredHogeが呼び出され、結果が$scope.hogeに格納される", function () {

        // Promiseを返す関数をもつサービスのモック
        var hogeServiceMock = {
            deferredHoge: function () {
                var deferred = $q.defer();
                deferred.resolve("HOGE");
                return deferred.promise;
            }
        };

        var $scope = $rootScope.$new();
        $controller("hogeController", {
            $scope: $scope,
            hogeService: hogeServiceMock
        });

        // この時点ではまだ初期値のまま
        expect($scope.hoge).toBe("");

        $rootScope.$digest();

        // $digest呼び出し後にPromiseの値が格納される
        expect($scope.hoge).toBe("HOGE");
    });
});
7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?