superagent-bluebird-promise cannot GET - promise

I'm using superagent-bluebird-promise, and the following gives me a 404 error, "cannot GET /v1/result". Have confirmed it works when I call it via Postman. What am I doing wrong?
it('should return a result', function(done){
stub.login(userId);
request.get('http://localhost:8080/v1/result/')
.then(function(res) {
console.log(res);
expect(res.body).to.have.lengthOf(1);
}, function(error) {
console.log(error);
expect(error).to.not.exist;
})
.finally(function(){
stub.logout();
done();
});
});

superagent-bluebird-promise is based on supertest
Assuming that stub.login sets some cookie, then you would require them in the next request.
For that you need an agent. (app may be optional)
var agent = request.agent(app)
agent.request(...)
Perform the login on the agent, then do the request on it too.

Related

Axios get request to Laravel endpoint from next.js

I have the following request to my laravel endpoint:
axios.get('http://localhost:8000/auth/login', {})
.then(function (response) {
console.log(response);
return {};
})
.catch(function (error) {
return {}
});
And my laravel endpoint set up as:
public function index() {
var_dump('login called.');die;
return response()->json(
[],
200
);
}
I Started my nextjs server (port 3000) and laravel server(8000), and when i browse to localhost:8000/auth/login in my browser I see "login called". however when I do that axios call, I get a status 200ok but no response data.
Request URL:http://localhost:8000/auth/login
Request Method:GET
Status Code:200 OK
Remote Address:127.0.0.1:8000
Referrer Policy:no-referrer-when-downgrade
Any idea what I am doing wrong?
Nothing is wrong with your code you are getting the response correctly, you see "login called" because you are accessing from a browser, therefore a browser has the cappability to render the html and you can see that.
But that axios call expects some json in return.
If you tweak the response a bit:
public function index() {
return response()->json(
['data' =>'Log in called'],
200
);
}
and if you twak axios response a bit
axios.get('http://localhost:8000/auth/login', {})
.then(function (response) {
console.log(response.data);
return {};
})
.catch(function (error) {
return {}
});
Inspect element open console and you will see 'Log in called'

Mocha chai request and express-session

When using two nested chai requests, session get lost.
chai.request(server)
.post('/api/v1/account/login')
.send({_email: 'test#test.com', _password: 'testtest'})
.end(function(err, res){
chai.request(server)
.get('/api/v1/user/me')
.end(function(err2, res2){
//here i should get the session, but its empty
res2.should.have.status(200);
done();
});
});
And i'm pretty sure that it's an error in my mocha test, because i tried it (the login and then retrieving the session) outside the test and the session is being setted.
express itself does not have any native session support. I guess you are using some session middleware such as https://github.com/expressjs/session.
Meanwhile, I guess you are using chai-http plugin to send HTTP request. In chai-http, in order to retain cookies between different HTTP requests (so that req.session can be available in express side), you need to use chai.request.agent rather than chai.
Here is a simple example for your code:
var agent = chai.request.agent(app);
agent.post('/api/v1/account/login')
.send({_email: 'test#test.com', _password: 'testtest'})
.then(function(res){
agent.get('/api/v1/user/me')
.then(function(res2){
// should get status 200, which indicates req.session existence.
res2.should.have.status(200);
done();
});
});
For chai.request.agent, you can refer to http://chaijs.com/plugins/chai-http/#retaining-cookies-with-each-request
In case anyone else comes across this issue, this approach worked for me using Mocha:
it("should...", () => {
return agent.post('/api/v1/account/login')
.send({_email: 'test#test.com', _password: 'testtest'})
.then(async res => {
const res2 = await agent.get('/api/v1/user/me')
res2.should.have.status(200);
})
.catch(error => {
throw error;
});
});

Karma Jasmine Error: Unexpected request: GET but i'm doing a POST

I am really struggling with for few hours now and can't just understant what's wrong with here's my code
My service:
(function(){
'use strict';
angular
.module('app')
.factory('register', register);
register.$inject = ['$http'];
function register($http){
var service = {
post: post
};
return service;
/////////////////////
function post(data){
return $http.post('/user/register', data)
.then(registerSuccess)
.catch(registerError);
function registerSuccess(response){
return response;
}
function registerError(error){
return error;
}
}
}
})();
and the spec file
describe('Register service', function(){
beforeEach(module('app'));
var service;
beforeEach(inject(function($http, $httpBackend, _register_) {
http = $http;
httpBackend = $httpBackend;
service = _register_;
}));
it('check if register service exist', function(){
expect(service).toBeDefined();
expect(service.post()).toBeDefined();
});
it('rrrr', function(){
httpBackend.expectPOST('/user/register', {u: 'xyz', password: 'pass' })
.respond(200, {'status': 'success'});
service.post({u: 'xyz', password: 'pass' })
.then(function(data){
expect(data.status).toBe(200);
});
httpBackend.flush();
});
});
If anyone can help me to understand why i am having this error
Error: Unexpected request: GET src/app/user/user.html
Thank you...
The app is fetching the templates for your routes/components/directives using XHR requests. The best way of getting around this is to use $templateCache.
You can use this preprocessor with karma to put the templates into a cache.
See this answer for more info.
The simplest solution is to use RegExp('.*.html'):
//setup backend so all .html requests get an 200 response
httpBackend
.whenGET(new RegExp('.*.html'))
.respond(function(){ return [200, 'XXX', {}] });
//setup spec specific behavior
httpBackend
.expectPOST('/user/register', {u: 'xyz', password: 'pass' })
Explanation:
This makes sure all .html GET requests are answered with 200 status reponse.
This will also make your 'Unexpected request' error go away.
Hope it helps.

Problems with $httpBackend.verifyNoOutstandingExpectation()

I have recently started writting unit tests using Karma + Karma-jasmine but I am having problems with the following tests:
describe("WEBSERVICE:", function () {
var webservice,
$httpBackend,
authRequestHandler,
webserviceURL = "http://localhost:8006/";
beforeEach(inject(function (Webservice, $injector) {
webservice = Webservice;
$httpBackend = $injector.get("$httpBackend");
authRequestHandler = $httpBackend
.when("GET", webserviceURL + "users/login")
.respond(200, "ok");
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it("should EXISTS", function () {
expect(webservice).toBeDefined();
});
it("should throw a WebserviceError if we are not logged in" , function () {
expect(function () {
webservice.item("negs", "RPT");
}).toThrow(webserviceAuthenticationError);
});
it("should NOT HAVE credentials when instantiated", function () {
expect(webservice.hasCredentials()).toBeFalsy();
});
it("should log in when valid credentials are given", function () {
$httpBackend.expectGET("users/login");
webservice.withCredentials("sam", "password");
});
});
It appears to be the following which creates the problem since all tests pass when I remove it:
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
I was just wondering if anyone could help me with this.
Thanks a lot.
The reason you having problems is with
$httpBackend.verifyNoOutstandingExpectation();
is due to your last test
it("should log in when valid credentials are given", function () {
$httpBackend.expectGET("users/login");
webservice.withCredentials("sam", "password");
});
having unsatisfied requests which you can see in this jsfiddle
Error: Unsatisfied requests: GET users/login
If you comment out
$httpBackend.verifyNoOutstandingExpectation()
your first three tests pass but the last one is amber as there is no expectations, see this fiddle.
WEBSERVICE:
should EXISTS
should throw a WebserviceError if we are not logged in
should NOT HAVE credentials when instantiated
SPEC HAS NO EXPECTATIONS should log in when valid credentials are given
In the AngularJS documentation it says
verifyNoOutstandingExpectation();
Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.
You will need to restructure that test so that
webservice.withCredentials("sam", "password");
makes a request through $httpBackend

SailsJs :: Keep sessions with mocha

I need to keep my sessions alive between to mocha requests.
After login, I store in the user id in the express session object :
req.session.user = user.id ;
On a browser, the session is kept without any question needed (tested with Postman).
But, I need to make my REST API reachable for an external app, and I would like not to have to authenticate for each request on my API.
Is there a way for me to be able to keep the session between two requests in mocha or via the client app of the API ?
Thanks by advance.
English is not my mother langage, I may have not been as clear as I would have wanted. So I can provide any information you might need to help me.
UPDATE
Thanks to Alberto, I figured out how to keep my sessions alive in Mocha with Supertest.
An agent keeps his sessions until its it destroyed, or the logout is requested.
What needs to be donne is use the same agent to login and for requesting the API.
What I did is :
var request = require('supertest'),
should = require('chai').should();
describe('ImageController', function() {
var agent = request.agent('http://localhost:1337') ;
before(function(done){
agent
.post('/auth/local')
.send({identifier: 'email', password: 'password'})
.end(function(err, res) {
if (err) return done(err);
done();
});
})
after(function(done){
agent
.get('/logout')
.end(function(err, res) {
if (err) return done(err);
done();
});
})
describe('POST /image', function(){
it('should return 201 for image creation after login', function (done) {
agent
.post('/image')
.send({name: 'test.png'})
.end(function (err, res) {
if (err) return done(err);
res.status.should.be.equal(201);
done();
});
});
});
});
Use supertest agent feature how can store cookies.
Has one example in supertest docs: https://github.com/tj/supertest#example
Sails.js example with super test example: https://github.com/albertosouza/sails-test-example
Test file example snipplet:
var request = require('supertest');
var assert = require('assert');
var authenticated;
describe('Example test', function() {
// use efore all to create custom stub data
before(function(done) {
// use supertest.agent for store cookies ...
// logged in agent
// after authenticated requests
//login and save one agent with your session cookies. Ex:
authenticated = request.agent(sails.hooks.http.app);
authenticated.post('/auth/login')
.send({
email: user.email,
password: user.password
})
.end(function(err) {
done(err);
});
});
describe('authenticated requests', function(){
it ('should access one protected route', function(done){
// use the authenticated agent to do authenticated requests
authenticated.get('/protected')
.expect(200)
.end(function(err, res) {
if (err) return done(err);
console.log('response:', res.text);
done();
});
});
});
});

Resources