我有一个在特定条件下播放声音的角度服务。我想模拟
window
的Audio
类来监视play
函数来检查它是否真的被调用了。
这是我的课:
import { Injectable } from "@angular/core";
import { SoundPreferencesStore } from "app/shared/stores/sound-preferences.store";
@Injectable({
providedIn: "root"
})
export class Service {
private readonly _audioPath: string = "assets/sounds/sound.mp3";
private readonly _audio: HTMLAudioElement;
public isSoundMuted: boolean;
constructor(
private readonly _soundPreferencesStore: SoundPreferencesStore
) {
this._audio = new Audio(this._audioPath);
this.isSoundMuted = this._soundPreferencesStore.isSoundMuted();
}
public playSound(): void {
if (!this.isSoundMuted) {
this._audio.play().catch(() => {});
}
}
}
我想模拟
Audio
类来检查当我使用 Jasmine 在我的服务中调用 play
函数时是否调用了 playSound
函数,如下所示:
describe("playSound", () => {
it("should play sound", async () => {
// Arrange
// Here is where I would use the mock
const audioMock = jasmine.createSpyObj<Audio>(["play"]);
service.isSoundMuted = false;
// Act
service.playSound();
// Assert
expect(audioMock.play).toHaveBeenCalled();
});
});
感谢您的帮助