2015-12-02 32 views
5

有誰知道如何使用角度2來測試基本火力點添加項目的基本單元測試。使用角度2的火力點添加單元測試

我使用打字稿,而不是基本的JavaScript爲我的代碼

這是我的測試:

export class AppComponent { 
    ref: Firebase; 
    refUsers: Firebase; 
    refProfiles: Firebase; 

    constructor(){ 
     this.ref = new Firebase("https://markng2.firebaseio.com"); 
     this.refUsers = new Firebase("https://markng2.firebaseio.com/users"); 
     this.refProfiles = new Firebase("https://markng2.firebaseio.com/profiles");  
    } 

    public addUser(newUser: Object): void{  
     this.refUsers.push(newUser,()=>{ 

     }); 
    } 
} 

這是我目前的測試:

import {it, iit, describe, expect, inject, injectAsync, beforeEachProviders, fakeAsync, tick } from 'angular2/testing'; 
import { AppComponent } from '../app/app'; 

describe('AppComponent',() => { 

    it('saves an item to Firebase',() => { 
     let refUsers = new Firebase(''); 

     let service = new AppComponent(); 

     spyOn(service.refUsers, 'push'); 
     service.addUser({ item: true }); 

     expect(service.refUsers.push).toHaveBeenCalled(); 
    }) 

}); 

這是我運行測試時得到的錯誤:

enter image description here

+0

似乎像一個配置問題 – AngularM

回答

2

三個步驟開始測試。

  1. Setup your testing environment。 Angular 2文檔有很好的指導。
  2. 編寫您的代碼。
  3. 編寫測試。

比方說,你創建一個名爲DataService類:

/// <reference path="typings/firebase/firebase.d.ts" /> 

export class DataService { 
    ref: Firebase; 
    constructor(theRef: Firebase) { 
     this.ref = theRef; 
    } 
    add(object: any) { 
     this.ref.push(object); 
    } 
} 

爲了測試它,你可以導入DataService並用茉莉花方法來測試add方法。

import {DataService} from './data-service'; 

describe('DataService',() => { 

    it('saves an item to Firebase',() => { 
     let ref = new Firebase(''); 
     let service = new DataService(ref); 
     // create a spy to use if push is called 
     spyOn(service.ref, 'push'); 
     service.add({ item: true }); 
     // expect that push was called 
     expect(service.ref.push).toHaveBeenCalled(); 
    }) 

}); 

測試Firebase方法的關鍵在於窺視它們。您無需測試Firebase的作用,只需您的代碼正確調用Firebase即可。

這裏的問題是您在單元測試中使用了完整的Firebase SDK。理想情況下,您希望使用模擬庫,因此您可以從Firebase SDK創建所需的任何功能模擬。

+0

嗨大衛,我已經添加了我的代碼上面,例如我的測試和我測試的代碼。 我似乎得到一個安裝問題。 – AngularM

+0

看來你並沒有包含所有的文件。這個問題雖然不是關於建立。我們儘量避免將一個問題轉化爲多個問題。如果您有其他問題,請解決此問題並開始另一個問題。 –

+0

好的沒有probs。我現在要創建另一個問題。 這是下一個問題的鏈接: http://stackoverflow.com/questions/34047379/unit-tests-for-firebase-files-not-included-issue – AngularM