Getting audio players to play their respective streams out of their element

As an example, we can easily add a test script called Jasmine to the buttons, using code like:

describe("Button A", function() {
  var app;
  beforeEach(function() {
    app = button_a;
  });
  it("has an init function", function() {
    expect(app.init).toBeDefined();
  });
});

We can then check if it switches play to pause when clicking on the button.

  var buttonSelector = ".playButtona";
  var button;
  beforeEach(function() {
    button = document.querySelector(buttonSelector);
  });
  it("switches play/pause images when the button is clicked", function() {
    expect(button.querySelector(".playa").classList.contains("hidea")).toBe(false);
    expect(button.querySelector(".pausea").classList.contains("hidea")).toBe(true);
    button.click();
    expect(button.querySelector(".playa").classList.contains("hidea")).toBe(true);
    expect(button.querySelector(".pausea").classList.contains("hidea")).toBe(false);
    button.click();
  });

And then we can test if the audio is paused or playing when we click the button.

  it("plays audio when the button is clicked", function () {
    var audio = document.querySelector("audio");
    expect(audio.paused).toBe(true);
    button.click();
    expect(audio.paused).toBe(false);
    button.click();
    expect(audio.paused).toBe(true);
  });

The nice thing about these tests is that if anything changes with the code that prevents any of those tests from working, the test runner (shown below the buttons) shows exactly what’s broken and why, which helps you to keep the code in a running state when making other improvements to the code.

2 Likes