首先,我还在学习Angular 4的基础知识,作为我正在做的实习的一部分;这对我来说还是新鲜事。
无论如何,我想模拟我在Angular组件的控制器中进行的实际HTTP请求的错误,在这样做时,我可以检查是否出现Bootstrap错误警报。 (假设它位于id为“updateErrorMessage”的div中)而不是编写后端以立即返回错误响应,我想使用Jasmine和Karma测试框架来模拟它。
我不能确切地说出组件是什么,但更通用的是,例如,来自名为“UpdateIndividualsPage”的组件的making a PUT request to update the individuals table on a Salesforce Industries database with JSON data。
基于this Salesforce developer question here,and this documentation page,在组件函数中发出请求的样板代码类似于:
this.http.post("https://na7.salesforce.com/services/apexrest/clinic01/v1/individual/", this.myJSON, options).map(response => {
}).catch((error: any) => {
}).subscribe();
如果响应出现错误,我会设置
errorOccurredUponUpdatingIndividualsDatabase = true
假设'errorOccurredUponUpdatingIndividualsDatabase'是UpdateIndividualsPage组件中的属性。
在updateindividualspage.component.pec.ts文件中,嵌套在describe函数调用中,我将测试用例的样板如下:
it('should display update error message upon sending improper data to Salesforce database', () => {
});
基本上,我的测试中的最后一个函数调用是,
expect(root_Element_Of_Component.querySelector('#updateErrorMessage').innerText).toBe('Error occurred upon updating the Salesforce Industries individuals database.');
我确实阅读了一些关于创建模拟HTTP错误的其他Stackoverflow问题,但我不完全确定,因为我还是新手。
Jasmine/Karma testing Angular 5 HTTP responses
mock http request in Angular 4
In Angular 5 testing, how to mock an http error?
我确实尝试了一些similar to the last test case in the initial code given in this StackOverflow question,除了我只是“失败:期望一个匹配的标准请求......”,这意味着我有一个URL不匹配。
这个测试用例是否有办法向该服务器发送实际的HTTP请求,但是这个测试框架会创建一个模拟错误响应?或者我是否真的需要创建一个MockBackend实例并让它将错误(作为HTTP响应)发送回前端,以在errorOccurredUponUpdatingIndividualsDatabase上引发标志以显示Bootstrap警报?
顺便说一下,后端已经实现了。
我更喜欢在单元测试中模拟HTTP调用。通过这种方式,我消除了其他变量。实际上你应该删除除了你正在测试的组件之外的所有其他变量。
对于模拟HTTP调用,您可以使用nock。
除了其他方法,最简单的方法可能是创建自己的后端页面,为您返回错误代码(404等)。