2016-02-19 49 views
1

PhantomJS不支持HTML5音頻標籤,這很難測試我的Angular2應用程序。我已經四處尋找解決方案,但不幸的是我一直無法找出一種方法來模擬音頻對象或以某種方式解決這個問題。我有一個Angular2服務,看起來像這樣:Angular2,TypeScript,PhantomJS - 找不到變量:音頻

import {Injectable} from 'angular2/core'; 

@Injectable() 
export class MyService { 
    var snd; 

    constructor() { 
    this.snd = new Audio('Assets/sound.wav'); 
    } 

    simpleFunction() { 
    return true; 
    } 
} 

我的測試是這樣的:

import {describe, expect, it} from 'angular2/testing'; 
import {Component} from 'angular2/core'; 
import {MyService} from 'my.service'; 

export function main() { 
    describe('My service',() => { 
    var myService: MyService = new MyService(); 

    it('should work',() => { 
     expect(myService.simpleFunction).toEqual(true); 
    }); 

    }); 
} 

當然這是一個簡化版本,但它證明了我有這個問題。當我運行我的測試,我收到此錯誤:

ReferenceError: Can't find variable: Audio 

我一直無法弄清楚如何從我的測試中發生避免這種。我在我的服務中試過這個:

if (Audio !== undefined) 

在'snd'變量被分配之前檢查,但我仍然得到相同的結果。

+0

我想你錯過了在課堂注入音頻? –

+1

@PankajParkar不,這是全球性的'window.Audio'構造函數。 – dfsq

回答

2

我想你可以嘲笑聽不到聲音,構造是這樣的:

import {describe, expect, it} from 'angular2/testing'; 
import {Component} from 'angular2/core'; 
import {MyService} from 'my.service'; 

export function main() { 
    describe('My service',() => { 

    beforeEach(() => { 
     if (!window.Audio) { 
      window.Audio = function() { 
       return { 
        play: function() {}, 
        pause: function() {}, 
        // ... etc 
       }; 
      }; 
     } 
    }); 

    var myService: MyService = new MyService(); 

    it('should work',() => { 
     expect(myService.simpleFunction).toEqual(true); 
    }); 

    }); 
} 
+0

我嘗試了類似的東西,但我得到這個:屬性音頻不存在類型窗口 – topherlicious

+0

是的,這是打字稿..你需要在窗口界面聲明屬性。例如,看看[這裏](http://stackoverflow.com/questions/12709074/how-do-you-explicitly-set-a-new-property-on-window-in-typescript)或將其添加到測試文件:https://jsfiddle.net/e5tt1htd/ – dfsq

相關問題