4

Angularjs を理解し始めたばかりで、アプリの構築を計画しています。私は実際には PHP プログラマーであり、JavaScript のバックグラウンドはほとんどありません。Angularjs は友人から紹介されました。アプリの機能が大きくなる前に、ジャスミン/カルマのテストも学習する必要があると警告されました. 今のところ、成功した場合にトークンを返す電子メールとパスワードを送信する $http 投稿があります。基本的に、成功するとユーザーはユーザー/プロファイル ページにリダイレクトされます

コントローラーコード:

function MainCtrl($scope, $location, Api, localStorageService, Security) {
 $scope.loginUser = function () {
    Api.authenticatePlayer({
        email    : $scope.main.email,
        password : $scope.main.password
    }).then(function (result){
        //success
        $location.path('/user/profile');
    }, function(result) {
        //error also this will catch error 400, 401, and 500
        console.log(result.data);
    });
 };
}

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

beforeEach(function() {
    module('myApp.services'),
    module("myApp.controllers")
});

beforeEach(inject(function($controller, $rootScope, $location, Api, localStorageService, $httpBackend, Security) {
    this.$location = $location;
    this.$httpBackend = $httpBackend;
    this.scope = $rootScope.$new();
    this.redirect = spyOn($location, 'path');

    $controller("MainCtrl", {
        $scope : this.scope,
        $location : $location,
        localStorageService : localStorageService,
        Security : Security
    });

}));

describe("successfully logging in", function () {
    it("should redirect you to /user/profile", function() {
        //arrange
        var postData = {
            email : this.scope.main.email,
            password : this.scope.main.password
        }
        this.$httpBackend.expectPOST('login', postData).respond(200);
        //act
        this.scope.loginUser();
        this.$httpBackend.flush();
        //assert
        expect(this.redirect).toHaveBeenCalledWith('/user/profile');
    });
});

ここに私のservice.jsコードがあります:

return {

  /**
   * Authenticate player
   * @param   object postData      Email and password of the user
   * @return object
   */
  authenticatePlayer: function(postData) {
    return $http({
      method  : 'POST',
      url     : api + 'auth/player',
      data    : postData,
      headers : {'Content-Type' : 'application/json'}
    });
  }
 }

テストスクリプトが失敗しました:(。エラーは次のとおりです。

Chrome 24.0 (Linux) controller: MainCtrl successfully logging in should redirect you to /user/profile FAILED
Error: Unexpected request: POST http://domain.com/auth/player
Expected POST login

誰でも助けてください。お手数をおかけして申し訳ありません。

4

1 に答える 1

2

したがって、これは、Api.authenticatePlayer期待しているものとは異なるパスを呼び出しているためです。

あなたのテストは代わりにこれを持つべきです:

this.$httpBackend.expectPOST('http://domain.com/auth/player', postData).respond(200);

基本的に、テストで$httpBackendは、API を呼び出すコードのモックです。「私のコードがこの URL を呼び出すときは、_で応答してください」と言うことができます。このコードでは、投稿が行われ、200 という空の応答が返されることを期待していると言っています。「200」を、サーバーが応答したふりをする json ペイロードに置き換えることができます。

于 2013-09-02T12:20:01.537 に答える