2017-08-04 24 views
1

我有一個組件,我正在進行單元測試,但我遇到了一個問題。我不知道如何在我的測試中模擬@Attribute裝飾器的工作。如何在ng2單元測試中模擬@Attribute裝飾器字符串提供程序?

Error: No provider for String!

我特別需要知道在我的測試 '提供'。

{ provide: ??, useValue: "" }

UPDATE

下面是測試設置

describe("MyComponent",() => { 
    let component: MyComponent; 

    beforeEach(() => { 
     this.injector = ReflectiveInjector.resolveAndCreate([ 
      { provide: ??, useValue: "" }, //@Attribute provider?? 
      ... // other mocked providers 
      MyComponent 
     ]); 

     component = this.injector.get(MyComponent); 
    }); 
    ... 
}); 
+0

你爲什麼要嘲笑呢? –

+0

@Maximus我沒有顯示整個組件的構造函數。這只是許多參數中的一個。這只是讓我感到悲傷。現在我們的單元測試使用注入器來創建我們正在測試的組件,但是我們可能需要脫離這種模式並手動創建組件的實例。我在技術上不需要嘲笑它。我只需要爲我的單元測試工作。 – Matt

+0

您可以在創建此組件的位置添加代碼嗎? – yurzui

回答

1

這應該爲你工作

{ provide: String, useValue: "test" }, 
AppComponent 

下面還將努力

import { Inject} from '@angular/core'; 

let token = 'handle'; 
Inject(token)(MyComponent, null, 0); // 0 is index of your parameter 

let injector = ReflectiveInjector.resolveAndCreate([ 
    { provide: token, useValue: "test" }, 

如果您有多個string PARAMS像

export class MyComponent { 
    constructor(
    @Attribute("handle") private handle: string, 
    @Attribute("handle2") private handle2: string) {} 

,那麼你可以這樣寫:

Inject('handle')(MyComponent, null, 0); 
Inject('handle2')(MyComponent, null, 1); 

let injector = ReflectiveInjector.resolveAndCreate([ 
    { provide: 'handle', useValue: "test" }, 
    { provide: 'handle2', useValue: "test2" }, 

Plunker Example

+0

This Works!對於獎勵積分,如果我有多個字符串參數,那麼我會爲我的字符串提供商使用工廠嗎? – Matt

+0

我更新了答案 – yurzui

相關問題