1

Jasmine 2 でテストしようとしている AngularJS ディレクティブがあります。テストの最初に定義したモック サービスを次に示します。

var Note = {
    getNotes: function (type, id) {
        console.log('I have been called')
    },
    save: function () {}
};

そして、ここに私のテストがあります:

beforeEach(function () {
    var html = "<notes id=\"productId\" type=\"'Product'\"></notes>";

    inject(function ($compile, $rootScope, $q, $injector, $templateCache) {
        $templateCache.put('tpl/blocks/notes.html', '<div>notes template</div>');

        $scope = $rootScope.$new();
        q = $q;
        $httpBackend = $injector.get('$httpBackend');
        $scope.productId = "123";

        elm = angular.element(html);
        $compile(elm)($scope);

        $scope.$apply();
        scope = angular.element(elm).isolateScope()
    });
});

it('should call service to get notes', function () {
    //GIVEN
    expect(scope.notes).toBe(undefined);
    spyOn(Note, 'getNotes').and.returnValue(new function () {
        var deferred = q.defer();
        scope.notes = [{'content': 'note1'}, {'content': 'note2'}];
        return deferred.promise;
    });

    //WHEN
    scope.$apply();

    //THEN
    expect(Note.getNotes).toHaveBeenCalled();
    expect(scope.notes.length).toBe(2);
});

最初の期待 (Note.getNotes が呼び出されることを期待する場所) を削除すると、テストに合格します。そうしないと、失敗します。ただし、console.log に出力されているため、サービスが呼び出されていることがわかります。

INFO [karma]: Karma v0.12.35 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.8 (Mac OS X 0.0.0)]: Connected on socket pPpiC59pcRGYeZDkmHH1 with id 30185266
WARN [web-server]: 404: /js/controllers/signin.js
......
LOG: 'I have been called'
PhantomJS 1.9.8 (Mac OS X 0.0.0) Notes directive should call service to get notes FAILED
        Expected spy getNotes to have been called.
            at /Users/mraible/dev/myapp/tests/unit/directives/notes_test.js:68
LOG: 'I have been called'
...
DUMP: 'background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: rgb(153, 255, 0); background-position: initial initial; background-repeat: initial initial; '
.
PhantomJS 1.9.8 (Mac OS X 0.0.0): Executed 11 of 11 (1 FAILED) (0.004 secs / 0.171 secs)
Warning: Task "karma:unit" failed. Use --force to continue.

Aborted due to warnings.

私の推測では、メソッドに引数があることを示すために、spyOn を変更する必要があります。

4

1 に答える 1