Angular2, TypeScript, PhantomJS - Can't find v

2019-08-13 03:01发布

问题:

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

  });
}