angularjs – 在端到端测试中捕获服务器JSON响应
发布时间:2020-12-17 17:14:55 所属栏目:安全 来源:网络整理
导读:我正在编写一个端到端测试,用 Protractor模拟用户身份验证.用户会感觉到她的凭据并单击“提交”按钮.因此,服务器在JSON响应中返回一个访问令牌,该响应可用于其他REST API调用.我想将此令牌保存到文件中. 关于捕获GET请求here的响应有类似的问题,但我不确定在
我正在编写一个端到端测试,用
Protractor模拟用户身份验证.用户会感觉到她的凭据并单击“提交”按钮.因此,服务器在JSON响应中返回一个访问令牌,该响应可用于其他REST API调用.我想将此令牌保存到文件中.
关于捕获GET请求here的响应有类似的问题,但我不确定在单击按钮后发送另一个请求是个好主意. 单击按钮后如何捕获响应? 解决方法
以下是关于如何捕获HTTP响应的想法. Protractor提供了一个方法browser.addMockModule()(
docs) – 它用于向页面添加自定义Angular模块,这些模块通常用于模拟输出请求并提供自定义响应.但是我们不需要模拟请求,只需要监听来自服务器的任何内容就足够了.它可以在Angular HTTP
interceptors的帮助下实现.拦截器用于捕获请求或响应,并在获取它的端点之前根据需要修改它.我们可以使用它们收集有关来自服务器的内容的信息,存储它,然后让响应继续进行而不做任何更改.由于此自定义模块和规范测试将在同一页面上运行,因此有关响应的信息可以存储在某个全局属性中.然后,当单击按钮时,可以将自定义脚本注入页面以通过browser.executeScript()(
docs)检索所需的响应.这是来源:
it('should intercept requests',function () { // Inject custom Angular module on a page // Script should be injected before you "browser.get()" the page browser.addMockModule('e2eHttp',function () { // Note: This function scope is not a Protractor environment angular .module('e2eHttp',[]) .config(function ($httpProvider) { // add custom interceptor to all requests $httpProvider.interceptors.push('e2eHttpInterceptor'); }) .factory('e2eHttpInterceptor',function () { return { response: function (response) { // name of the global property to store responses var global = 'e2eHttpResponses'; // responses will be grouped by url // but you can use data from "response.config" to adapt it // it has a lot of info about response headers,method,etc var url = response.config.url; window[global] = window[global] || {}; window[global][url] = window[global][url] || []; window[global][url].push(response); // store response // proceed without changing response return response; } }; }); }); // Load the page browser.get('#/auth/login'); $('#submit').click(); // If we are sure that response has come,then extract it browser.executeScript(function () { // Note: This function scope is not a Protractor environment var global = 'e2eHttpResponses'; var uri = 'api/auth/login.json'; // extract array of stored responses for required uri var responses = (window[global] && window[global][uri]) || []; // return responses to spec return responses; }).then(function (responses) { // and finally,we are now able to get all information we need // about response,and in your case,save it to a file console.log(responses); var data = responses[0].data; // first response body as a string }); // remove injected module not to break another specs browser.removeMockModule('e2eHttp'); }); 您可以将设置和注入调用移动到某些实用程序模块,因此测试规范将是干净的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读