2015-09-22 85 views
2

我想測試下的服務和似乎有麻煩匹配的模擬響應:茉莉花+角測試:類型錯誤:「未定義」不是一個對象

public getCustomerDetails(customerID:string): ng.IPromise<ICustomerDetails> { 
    return this.testService.getCustomerDetails(customerID).then((customerResponse:ICustomerResult) => { 

     var customer = customerResponse.customers; 

     var customerDetailsResult:ICustomerDetails = { 
      customerNumber: customer.displayCustomerNumber, 
      name: customer.name, 
      userId: customer.buId, 
      customerType: customer.type, 
      address: customer.displayAddress 
     }; 

     return customerDetailsResult; 
    }); 
} 

這裏是茉莉花代碼:

describe('CustomerService',() => { 
    var mockTestService: any = {}; 
    var $q: ng.IQService; 
    var createCustomerDetailsService; 
    var customerDetailsService; 
    var createResolvedPromise; 
    var resolvePromises; 

    var serviceResponse = { 
     customerNumber: 'string', 
     name: 'name', 
     userId: 'buId', 
     customerType: 'type', 
     address: 'displayAddress' 
    }; 

    var rootScope; 

    beforeEach(() => { 
     module('app.customer'); 

     inject((_$q_, $injector) => { 
      this.$q = _$q_; 
      rootScope = $injector.get('$rootScope'); 

      createResolvedPromise = (result) => { 
       return this.$q.when(result); 
      }; 

      resolvePromises =() => { 
       rootScope.$apply(); 
      }; 

      createCustomerDetailsService =() => { 
       return new app.customer.CustomerService(
        mockRnsService); 
      }; 
     }); 

    }); 


    it('WILL search by customer ID and return a customers details',() => { 
     var searchResponsePromise; 

     mockTestService.getCustomerDetails = jasmine.createSpy("getCustomerDetails").and.callFake(createResolvedPromise); 
     customerDetailsService = createCustomerDetailsService(); 
     searchResponsePromise = customerDetailsService.getCustomerDetails('12345678'); 
     resolvePromises(); 

     expect(searchResponsePromise).toEqual(serviceResponse); 
    }); 

}); 

我得到的錯誤是:

TypeError: 'undefined' is not an object (evaluating 'customer.displayCustomerNumber')

任何人都可以告訴我爲什麼我得到這個錯誤?謝謝你的幫助。

回答

2

createResolvedPromise設置getCustomerDetails返回一個承諾,其中包含您傳入的參數的值 - 在此例中爲'12345678'。這意味着customerResponse的值是'12345678'。因此,customer取自customerResponse.customers的值是未定義的,因爲字符串上沒有屬性customers。所以錯誤發生在您試圖評估customer.displayCustomerNumber時,因爲customer未定義。

+0

Thankyou @TomDoesCode,這是有道理的。真的很感謝你的幫助! – Desmond