Angular2, TypeScript, PhantomJS - Can't find variable: Audio

纵然是瞬间 提交于 2019-12-11 14:01:57

问题


PhantomJS doesn't support HTML5 Audio tags, which is making it difficult to test my Angular2 app. I've looked around for a solution, but unfortunately I haven't been able to figure out a way to mock the Audio object or somehow get around this. I have an Angular2 service that looks like this:

import {Injectable} from 'angular2/core';

@Injectable()
export class MyService {
  var snd;

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

  simpleFunction() {
    return true;
  }
}

My test looks like this:

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);
    });

  });
}

This is of course a simplified version, but it demonstrates the issue I'm having. When I run my test, I receive this error:

ReferenceError: Can't find variable: Audio

I haven't been able to figure out how to avert this from happening in my tests. I have tried this in my service:

if (Audio !== undefined) 

To check before the 'snd' variable is assigned, but I still got the same result.


回答1:


I think you could mock missing Audio constructor like this:

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);
    });

  });
}


来源:https://stackoverflow.com/questions/35510515/angular2-typescript-phantomjs-cant-find-variable-audio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!