Я пытаюсь создать тестовую установку для огурцов с помощью Node.js, которая может протестировать любой веб-сайт с помощью iframe. Обычно iframe не подходит из-за ограничений безопасности кросс-скриптов. Однако, если бы это было возможно (, я уверен, что это возможно. И я верю, что вы найдете решение )для получения веб-сайта, являющегося целевым для теста, через запрошенный URL-адрес, когда запрашивается конкретное имя URL-адреса, чтобы iframe загружался с копией целевого объекта теста. В основном это стандартный сервер node.js, который извлекает определенные страницы на основе req.url. Сродни маршрутизатору запросов адреса.
Вот моя вопиющая попытка сделать именно это. Получение тестовой страницы через. URL работает. Но у меня проблема с переключением с http-сервера на объект подключения. Есть ли способ «накормить» соединение ответом http-сервера?
PS. Я также создал решение с двумя серверами node.js. Узел 1 извлек тестовую цель и смешал ее с тестовой страницей огурца. Узел 2, на котором проводится тест на огурец. Это решение работает. Но это создает проблемы на веб-сайтах, где возникают конфликты имен javascript. Вот почему решение iframe, которое решает эту проблему путем инкапсуляции, более привлекательно.
var http = require('http');
var connect = require('connect');
var port = process.env.PORT || 8788;
var server = http.createServer(function(req, webres)
{
var url = req.url;
console.log(url);
if(url == '/myWebsiteToBeTestedWithCucumberJS')
{
// Load the web site to be tested "myWebsiteToBeTestedWithCucumberJS"
// And update the references
// Finaly write the page with the webres
// The page will appear to be hosted locally
console.log('Loading myWebsiteToBeTestedWithCucumberJS');
webres.writeHead(200, {'content-type': 'text/html, level=1'});
var options =
{
host: 'www.myWebsiteToBeTestedWithCucumberJS.com,
port: 80,
path: '/'
};
var page = '';
var req = http.get(options, function(res)
{
console.log("Got response: " + res.statusCode);
res.on('data', function(chunk)
{
page = page + chunk;
});
res.on('end', function()
{
// Change relative paths to absolute (actual web location where images, javascript and stylesheets is placed)
page = page.replace(/ href="\/\//g , ' href="/');
page = page.replace(/ src="\//g , ' src="www.myWebsiteToBeTestedWithCucumberJS.com');
page = page.replace(/ data-src="\//g , ' data-src="www.myWebsiteToBeTestedWithCucumberJS.com');
page = page.replace(/ href="\//g , ' href="www.myWebsiteToBeTestedWithCucumberJS.com');
webres.write(page);
webres.end('');
});
});
}
else
{
// Load any file from localhost:8788
// This is where the cucumber.js project files are hosted
var dirserver = connect.createServer();
var browserify = require('browserify');
var cukeBundle = browserify({
mount: '/cucumber.js',
require: ['cucumber-html', './lib/cucumber', 'gherkin/lib/gherkin/lexer/en'],
ignore: ['./cucumber/cli', 'connect']
});
dirserver.use(connect.static(__dirname));
dirserver.use(cukeBundle);
dirserver.listen(port);
}
}).on('error', function(e)
{
console.log("Got error: " + e.message);
});
server.listen(port);
console.log('Accepting connections on port ' + port + '...');