1

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.

John
  • 1
  • 13
  • 98
  • 177
topherlicious
  • 173
  • 3
  • 13

1 Answers1

2

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

  });
}
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • I attempted something similar, but I get this: Property Audio does not exist on type Window – topherlicious Feb 19 '16 at 17:53
  • yea, this is typescript.. you need to declare property on the window interface. For example look [here](http://stackoverflow.com/questions/12709074/how-do-you-explicitly-set-a-new-property-on-window-in-typescript) or add this to the test file: https://jsfiddle.net/e5tt1htd/ – dfsq Feb 19 '16 at 21:32