簡體   English   中英

茉莉花單元測試廠

[英]Jasmine unit test factory

我是茉莉花測試的新手,在這里我想在工廠中測試$ resources,所以我首先有了這個工廠:

 angular.module('starter.services', []) .factory('API', function($rootScope, $resource) { var base = "http://192.168.178.40:8000/api"; return { getGuestListForH: $resource(base + '/guests/:id/:wlist', { id: '@id', wlist: '@wlist' }) } }); 

和我的測試:

 beforeEach(module('starter.services')); describe('service: API resource', function() { var $scope = null; var API = null; var $httpBackend = null; beforeEach(inject(function($rootScope, _API_, _$httpBackend_) { $scope = $rootScope.$new(); API = _API_; $httpBackend = _$httpBackend_; $httpBackend.whenGET('http://192.168.178.40:8000/api/guests').respond([{ id: 1, name: 'a' }, { id: 2, name: 'b' }]); })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('expect all resource in API to br defined', function() { $httpBackend.expect('http://192.168.178.40:8000/api/guests'); var dd = API.getGuestListForH.query(); expect(dd.length).toEqual(2); expect(API.getGuestListForH).toHaveBeenCalled(); }); }); 

我得到了結果:

  • 預期0等於2
    • 可能是間諜,但得到了功能 。這里出什么問題。我想在工廠測試資源的最佳方法是什么?

即使沒有$rootScope和您完成的所有其他變量聲明,您的測試也可以執行。

而且,由於您正在為Service的方法編寫測試,因此不要expectexpecttoHaveBeenCalled ,而應該調用它並期望結果有所作為。

像這樣:

describe('Service: starter.services', function() {
    beforeEach(module('starter.services'));
    describe('service: API resource', function() {
        beforeEach(inject(function(_API_, _$httpBackend_) {
            API = _API_;
            $httpBackend = _$httpBackend_;

            $httpBackend.whenGET('http://192.168.178.40:8000/api/guests').respond([{
                id: 1,
                name: 'a'
            }, {
                id: 2,
                name: 'b'
            }]);
        }));

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

        it('expect all resource in API to br defined', function() {
            var dd = API.getGuestListForH.query();
            $httpBackend.flush();
            expect(dd.length).toEqual(2);
        });
    });
});

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM