2015-07-10 51 views
1

我正在嘗試對我有的http請求進行一些單元測試。我發佈的數據到第二個參數在我的HTTP POST請求

var data = {} /* some data object */; 
return $http.post(url, data); 

但後來當我的單元測試,我不能檢查,如果數據使得它

$httpBackend.expectPOST(cfcmApiPath + 'book/addDocument').respond('IGNORE_ME'); 
var httpPromise = docComponentRestSvc.addDocumentToBook(22063, doc); 
$httpBackend.flush(); 

這將導致一個錯誤:

Error: Expected POST http://192.168.33.10/mymy/api/book/addDocument with different data 
    EXPECTED: {"eventId":22063,"sequenceIndex":0,"name":"Nombre","type":"FRONT_OUTSIDE_COVER","value":"Que Tal, Amigo?"} 

奇怪的是,當我正常運行它時,調用似乎正在工作。這就是爲什麼我想看看請求數據有什麼問題。但是,我不知道該怎麼做。任何建議?

有關進一步的細節和可能相關的是,我有一個'核心'庫,我試圖實現的地方基本上我想從庫中使用http來使用,因爲庫做了一些轉換並將東西保存在緩存中似乎沒有從主模塊自動攔截。

回答

0

尋找response.data在測試或其他 - 取決於你沒有與我們分享的代碼。

angular.module('document', []) 
 
.service('docComponentRestSvc', function($http) { 
 
    this.addDocumentToBook = function(data) { 
 
    return $http.post('book/addDocument', data) 
 
    } 
 
}) 
 

 
describe('document component', function() { 
 

 
    var $httpBackend, docComponentRestSvc 
 

 
    beforeEach(module('document')); 
 

 
    beforeEach(inject(function(_$httpBackend_, _docComponentRestSvc_) { 
 
    $httpBackend = _$httpBackend_; 
 
    docComponentRestSvc = _docComponentRestSvc_; 
 
    })); 
 

 

 
    it('POSTs new document', function() { 
 
    var doc = { 
 
    name: 'Nombre' 
 
    }; 
 
    var mockResponse = 'IGNORE_ME'; 
 
    $httpBackend.expectPOST('book/addDocument').respond(mockResponse); 
 
    docComponentRestSvc.addDocumentToBook(22063, doc).then(function(response) { 
 
     expect(response.data).toBe(mockResponse); 
 
    }) 
 
    $httpBackend.flush(); 
 
    }); 
 

 
    afterEach(function() { 
 
    $httpBackend.verifyNoOutstandingExpectation(); 
 
    $httpBackend.verifyNoOutstandingRequest(); 
 
    }); 
 

 
})
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" /> 
 
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script> 
 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>