13

$scope値を取得して別の状態に送信するコントローラーがあります。

controllers.controller('SearchController', ['$scope', '$state', '$stateParams',
function($scope, $state, $stateParams) {
    $scope.search = function() {
        $stateParams.query = $scope.keyword;
        $state.go('search', $stateParams);
    };
}]);

この検索方法の単体テストを行う方法がわかりません。when($state.go('search', $stateParams)).then(called = true);go メソッドが呼び出されたことを確認するか、またはKarma/AngularJS で何らかの操作を行うにはどうすればよいですか?

4

1 に答える 1

34

これらは両方とも、ジャス​​ミンのスパイでできることのように聞こえます。

describe('my unit tests', function() {
    beforeEach(inject(function($state) {
        spyOn($state, 'go');
        // or
        spyOn($state, 'go').andCallFake(function(state, params) {
            // This replaces the 'go' functionality for the duration of your test
        });
    }));

    it('should test something', inject(function($state){
        // Call something that eventually hits $state.go
        expect($state.go).toHaveBeenCalled();
        expect($state.go).toHaveBeenCalledWith(expectedState, expectedParams);
        // ...
    }));
});

ここに良いスパイチートシートがありますhttp://tobyho.com/2011/12/15/jasmine-spy-cheatsheet/または実際の Jasmine ドキュメントはこちら.

スパイを使用することの良い点は、明示的に指示しない限り、実際に状態遷移を実行することを回避できることです。URL が変更された場合、状態遷移は Karma でのユニット テストに失敗します。

于 2013-10-10T01:33:39.513 に答える