If the reader
的行为正在呼唤onerror
when readAsDataURL
失败了,这应该做:
spyOn(newPracticeQuestionComponent.reader, 'readAsDataURL').and.callFake(() => {
newPracticeQuestionComponent.reader.onerror();
});
由于这将作为同步调用运行,因此您可以在测试结束时简化断言(遵循三个 A),如下所示:
// Arrange
const newPracticeQuestionComponent = component;
spyOn(newPracticeQuestionComponent, 'handleReaderError');
spyOn(newPracticeQuestionComponent.reader, 'readAsDataURL').and.callFake(() => {
newPracticeQuestionComponent.reader.onerror();
});
let file1 = new File(["foo1"], "foo1.txt");
// Act
newPracticeQuestionComponent.handleFileSelect([file1]);
// Assert
expect(newPracticeQuestionComponent.handleReaderError).toHaveBeenCalledWith({ type: 'abort' });
但我不建议期望参数传递给函数,event.type
, 因为它是另一个单位的规格我们目前没有测试。 (我们正在测试newPracticeQuestionComponent
不是的行为reader
用事件调用错误)
嘲笑的行为reader
可能不是最好的方法。这取决于您想要针对该单元进行测试的内容。
如果我们想变得极其独立,newPracticeQuestionComponent
应该一无所知reader
的行为甚至回调错误,该单元唯一应该知道的是设置onerror
回调,你可以断言你设置了onerror
读者正确。
// Arrange
const newPracticeQuestionComponent = component;
spyOn(newPracticeQuestionComponent.reader, 'readAsDataURL');
let file1 = new File(["foo1"], "foo1.txt");
// Act
newPracticeQuestionComponent.handleFileSelect([file1]);
// Assert
expect(newPracticeQuestionComponent.reader.onerror).toBe(newPracticeQuestionComponent.handleReaderError);
我不是测试方面的专家,但根据许多因素编写上面和下面的示例之类的测试似乎是有利有弊的。
希望这可以帮助 :)