我有一个angular服务,它在特定条件下播放声音。我想模拟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在我的服务中调用playSound
函数时,是否调用了play
函数,如下所示:
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();
});
});
谢谢你的帮助
1条答案
按热度按时间plicqrtu1#
你可以尝试测试
play()
是否被调用,如果你想在服务中添加某种标志,你不能模拟一个类属性,你甚至不能从外部访问一个private
属性,即使在测试服务本身。也许有一个更好,更聪明的方法,但是,我会像下面这样测试它:
服务项目
规格