I'm writing an end-to-end test that simulates user authentication with Protractor. A user feels in her credentials and clicks a Submit button. As a result, the server returns an access token in a JSON response that can be used for other REST API calls. I'd like to save this token to a file.
There's a similar question on capturing a response of a GET request here, but I'm not sure it's a good idea to send another request after I click the button.
How can I capture the response after a button click?
答案 0 :(得分:3)
以下是关于如何捕获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');
});
您可以将设置和注入调用移动到某些实用程序模块,因此测试规范将是干净的。