Is there a way to change the proxy between requests (for the same casper object):
somthing like that:
var casper=require('casper').create({
clientScripts: ["lib/js/jquery.min.js"],
// other settings...
});
casper.start("http://www.site1.com",function(){
casper.setProxy("http://xxx.xx.xx.xx:80"); // is there somthing like that ?
casper.thenOpen("http://www.site2.com",function(){ // through the proxy i set above...
// some code...
});
});
casper.run(function(){casper.exit();});
Related
Let's say I have a small piece of code:
var express = require('express');
var app = express();
app.get('/', function(req, res){
//I want to acccess 'req' and get info whether it's an AJAX call
});
app.listen(3000);
When I go inside the app.get(..) function, I want to know if the get request sent is an AJAX call. What is the field in the object 'req' that can tell me this?
The header X-Requested-With: XMLHttpRequest HTTP header is not automatically added to an AJAX request, either with fetch or with the old-fashioned use of the XMLHttpRequest object. It is often added by client libraries such as jQuery.
If the header is present, it is represented in Express by request.xhr.
If you want to add it to the request (the simplest solution to this problem) you can add it as a custom header with fetch:
fetch(url, {
headers: {
"X-Requested-With": "XMLHttpRequest"
}
});
This will now be reflected in req.xhr.
A better solution is to set the Accept header to a sensible value. If you want JSON to be returned, set Accept to application/json:
fetch(url, {
headers: {
"Accept": "application/json"
}
});
You can then test for this with req.accepts:
switch (req.accepts(['html', 'json'])) { //possible response types, in order of preference
case 'html':
// respond with HTML
break;
case 'json':
// respond with JSON
break;
default:
// if the application requested something we can't support
res.status(400).send('Bad Request');
return;
}
This is much more powerful than the req.xhr approach.
app.get('/', function(req, res){
//I want to acccess 'req' and get info whether it's an AJAX call
if(req.xhr){
//the request is ajax call
}
})
var express = require('express');
var app = express();
app.get('/', function(req, res){
var isAjax = req.xhr;
});
app.listen(3000);
Do both of these serve the same purpose? Why are they both used in, for example, this tutorial https://codeforgeek.com/2015/07/unit-testing-nodejs-application-using-mocha/ ?
Edit, Looking at the following code:
var supertest = require("supertest");
var should = require("should");
// This agent refers to PORT where program is runninng.
var server = supertest.agent("http://localhost:3000");
// UNIT test begin
describe("SAMPLE unit test",function(){
// #1 should return home page
it("should return home page",function(done){
// calling home page api
server
.get("/")
.expect("Content-type",/json/)
.expect(200) // THis is HTTP response
.end(function(err,res){
// HTTP status should be 200
res.status.should.equal(200);
// Error key should be false.
res.body.error.should.equal(false);
done();
});
});
});
Is it necessary to have
.expect(200)
and
res.status.should.equal(200);
? What is the difference?
The .expect(200) part is using the supertest facility for verifying data. the object.should.equal(value) part is using shouldJS for verification.
I prefer utilizing shouldJS in the .end() because it allows me to do a bit of data manipulation, testing, logging, etc, as needed.
Do note the following from: https://www.npmjs.com/package/supertest
If you are using the .end() method .expect() assertions that fail will not throw - they will return the assertion as an error to the .end() callback.
So, in the example code you show above, if .expect("Content-type",/json/) or .expect(200) fails, there is nothing in the .end() to catch it. A better example would be:
var supertest = require("supertest");
var should = require("should");
// This agent refers to PORT where program is runninng.
var server = supertest.agent("http://localhost:3000");
// UNIT test begin
describe("SAMPLE unit test",function(){
// #1 should return home page
it("should return home page",function(done){
// calling home page api
server
.get("/")
.expect("Content-type",/json/)
.expect(200) // THis is HTTP response
.end(function(err,res){
// NOTE: The .expect() failures are handled by err and is
// properly passed to done. You may also add logging
// or other functionality here, as needed.
if (err) {
done(err);
}
// Error key should be false.
res.body.error.should.equal(false);
done();
});
});
});
Update to answer the question in the comment and provide a prettier response here:
Question: Would doing something like .expect(200, done) catch the error then?
Answer: The short answer is, "Yes". On the same page I quoted above, it has the following:
Here's an example with mocha, note how you can pass done straight to
any of the .expect() calls:
describe('GET /user', function() {
it('respond with json', function(done) {
request(app)
.get('/user')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, done);
});
});
Technically speaking there's no difference and I think you should stick to .expect(200) just like supertest examples suggest: https://github.com/visionmedia/supertest
I have a working ractive component test case already with mocha using sinon ans able to mock an ajax call but with the help of setTimeout(function(){}, 100) and I dont like using it.
beforeEach(function () {
this.container = document.createElement('div');
document.body.appendChild(this.container);
this.server = sinon.fakeServer.create();
this.server.respondWith(
"GET",
"/api/url",
[
200,
{ "Content-Type": "application/json" },
'{"data": []}'
]
);
});
afterEach(function () {
document.body.removeChild(this.container);
});
it("should fetch data from server", function (done) {
var server = this.server;
var Component = require('rvc!path/to/component');
var component = new Component({
el: this.container,
});
setTimeout( function() {
server.respond();
expect(component.findAll('.list li').length).to.equal(7);
done();
}, 100);
});
As you can see in the code above, I'm using the setTimeout to make sure that the ajax call (mock) was made before having the actual test of the component.
Is there a way that I can eliminate the setTimeout having the same effect? Thanks!
Assuming that your http request is happening in the component, then it won't get the data until the next tick of the event loop.
One approach is to use setTimeout as you have done, but you probably can lower the timeout (use autoRespondAfter to adjust the sinon response delay).
If your component code supports it, an approach that seems well suited to your use case from the sinon fakeServer docs would be to use the respondImmediately option:
If set, the server will respond to every request immediately and
synchronously. This is ideal for faking the server from within a test
without having to call server.respond() after each request made in
that test. As this is synchronous and immediate, this is not suitable
for simulating actual network latency in tests or mockups.
this.server = sinon.fakeServer.create({ respondImmediately: true })
// now no need to call server.respond() and calls are returned synchronously!
var socket = io.connect('http://ip:port');
socket.on('connect', function(){});
socket.on('message', function(message) {
some code..
});
socket.on('disconnect', function(){ });
Here i don't want to use hardcoded ip address.so i need to get from config file.suggest me to solve this one.Thanks in advance.
You can store the IP/PORT in a config file on the server and then pass those variables to the frontend using the 'locals' function in expressjs.
This will make that information available to your view renderer, which in turn can write the data in your templates.
How best to set up your config file is really up to your specific use-case.
# Server Side
app.locals.hosts = {
http: 'localhost:3000',
file: 'localhost:3001',
websocket: 'localhost:2000'
}
# Client Side (rendered via mustache)
var socket = io.connect('ws://#{hosts.websocket}');
I want to send the filepath of a file on my server to the client in order to play it using a media player. How can I retrieve that string on the client side in order to concatenate it in the src attribute of a <video element without using sockets?
Server snippet:
res.set('content-type', 'text/plain');
res.send('/files/download.mp4');
This is how you make a request to the server without any frameworks. "/path_to_page" is the route you set to the page that is supposed to process the request.
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path_to_page', true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(this.responseText); // output will be "/files/download.mp4"
}
};
xhr.send();
}
You might also want to send some params.
var formdata = new FormData();
formdata.append("param_name", "value");
So you might for instance want to send the filename or such.
You just need to change 2 lines from the first code snippet. One would be
xhr.open('POST', '/path_to_page', true); // set to post to send the params
xhr.send(formdata); // send the params
To get the params on the server, if you are using express, they are in req.body.param_name
Which framework are you using??
You can declare base path of your project directory in ajax and the followed by your file.
jQuery.ajax({
type: "GET",
url: "/files/download.mp4",
});
Since you are using express (on node), you could use socket.io:
Server:
var io = require('socket.io').listen(80),
fs = require('fs');
io.sockets.on('connection', function (socket) {
socket.on('download', function(req) {
fs.readFile(req.path, function (err, data) {
if (err) throw err;
socket.emit('video', { video: data });
});
});
});
Client:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
...
// request a download
socket.emit('download', { path: '/files/download.mp4' });
// receive a download
socket.on('video', function (data) {
// do sth with data.video;
});
...
</script>
Edit: didnt notice you didnt want to use sockets. Still it is a viable solution.