EzDevInfo.com

frisby

Frisby is a REST API testing framework built on node.js and Jasmine that makes testing API endpoints easy, fast, and fun. REST API Testing—Frisby.js

Should I use FrisbyJS for my REST API testing? [closed]

I am developing a complicated project with microservice architecture (only provides Rest API). So I need to make sure that the system works stably in development, staging, and production after having a deployment.

I think that a testing framework as Frisby can help me prevent issues. Do you have any suggestion for my case?

Thank you in advance.


Source: (StackOverflow)

How do I use frisby.js with SSL client certificates?

I have a question about the use of Frisby.js with a REST service that uses SSL client certificates.

If I use the Request package to talk to the service, I can do something like this:

request.get(URL, {
  agentOptions: {
    // Or use `pfx` property replacing `cert` and `key` when using private key, certificate and CA certs in PFX or PKCS12 format:
    pfx: fs.readFileSync(pfxFilePath),
    passphrase: 'password',
    ca: fs.readFileSync(caFilePath)
  }
});

Since Frisby uses request, I assume I can do something similar in a Frisby test, but I can’t seem to get the syntax correct.

Can you suggest something that might work? Thanks...


Source: (StackOverflow)

Advertisements

Is there a way to send a JPG with Jasmine NodeJS?

I'm trying to test out my API using FrisbyJS (which sits on top of Jasmine for Node). I was wondering if anyone knew how to submit/send an image using Jasmine?

http://frisbyjs.com/

My current code is...

var frisby = require('frisby');

var URL = 'http://localhost/api';

frisby.globalSetup({
  request: {
  headers: {
   'Content-Type': 'application/x-www-form-urlencoded',
   'Accept': 'application/json',
   'api': 'key'
  }
 },
 timeout: (30 * 1000)
});

frisby.create('submit an image')
  .post(URL + 'image', {images: '@test.jpg'}, {method: 'POST'})
  .expectStatus(200)
  .afterJSON(function(cart){
    console.log('made it!');
  })
}).toss();

And I get the following error:

  1) Frisby Test: submit an image
[ POST http://localhost/api ]
  Message:
   timeout: timed out after 30000 msec waiting for HTTP Request timed out before completing
   Stacktrace:
    undefined

    Finished in 31.458 seconds

And yes, the image test.jpg does exist in the same folder :) as the spec file and where I'm executing the spec itself (jasmine-node .).


Source: (StackOverflow)

Can you point me to an example of using cucumber.js with frisby.js?

We would like to use frisby.js withing cucumber steps. Can anyone point me to an example which does the same?

Thanks


Source: (StackOverflow)

jasmine is not defined

I am trying to run a rest API test on Enide Studio using friby.js and Jasmine.

I got this error:

C:\Users\xxxx\AppData\Roaming\npm\node_modules\frisby\lib\frisby.js:1125
jasmine.Matchers.prototype.toMatchOrBeNull = function(expected) {
^
ReferenceError: jasmine is not defined
    at Object.<anonymous> (C:\Users\xxxx\AppData\Roaming\npm\node_modules\frisby\lib\frisby.js:1125:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (C:\Users\xxxx\Desktop\Enide-Studio-2014.17-luna-SR1-win64\ws\SampleProject\.settings\sample_spec.js:4:12)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)

I tried the same script in note pad and ran using CLI, it worked well.

Please help me as I need to run this on a IDE.


Source: (StackOverflow)

Accessing JSON values with jasmine-node / frisby

I am trying to construct a test that will validate the error message received for a bad request to an API. I am using node-jasmine and frisby to write the tests but having trouble accessing the JSON values with dot notation.

 var frisby = require('frisby');
    frisby.create('JSON Error')
      .put('url', {
      }, {json: true})
      .expectStatus(400)
      .expectHeaderContains('content-type', 'application/json')
      .auth('username', 'password')
      .afterJSON(function (body) {
        //changed values
        expect(body.error.newEmail).toMatch('missing-required-key'),
        expect(body.error.oldEmail).toMatch('missing-required-key')
      })
    .toss();

Expected JSON response body

{
"error": {
"newEmail": "missing-required-key",
"oldEmail": "missing-required-key"
}
}

Test results in following error:

Cannot read property newEmail of undefined

I have wrote a similar test in Postman which works, I am trying to convert these tests into something that can be used by node.js.

Postman working example:

var body = JSON.parse(responseBody);

//error messages

var newEmailError = body.error.newEmail;
var oldEmailError = body.error.oldEmail;

tests["New Email Error Message"] = newEmailError === "missing-required-key";
tests["Old Email Error Message"] = oldEmailError === "missing-required-key";

Source: (StackOverflow)

frisbyjs, returning 415 instead of 200

I just started using frisbyjs to test a rest service we are building out. I'm getting an error and that it says it's expecting a 415 instead of 200. My code looks like:

var frisby = require("frisby");
var apiUrl = // api url
frisby.create("GET resource by id " + "43")
    .get(apiUrl + "/book/43")
    .expectStatus(200)
    .toss();

The exact error message is:

Expected 415 to equal 200.

When I put the exact url that jasmine spits out to me when I run my test into a browser, or try it as a GET request in Postman on Chrome, it works and I get a 200 back. For some reason I get a 415 though for my call. Is there something I am missing? Thanks.

Edit: Tried to debug some more and if I just do

frisby.create("GET resource by id " + "43")
    .get(apiUrl + "/book/43")
    .inspectJSON()
    .toss();

I get this error:

Error parsing JSON string: Unexpected end of input

Which makes me thing that our rest service is doing something funny. However when I view this url in a browser or postman like I said, it works fine. Thanks.


Source: (StackOverflow)

Javascript promise not executing in desired order

I have been trying to execute a number of tests for an API, for this example it required my account details to be updated. When I run the test the retrieveAccount call is sometimes run before my putRequest making the tests fail. What am I doing wrong?

var frisby = require('frisby');
var url = require('endpoints.js');
var auth = require('auth.js');
var oracledb = require('oracledb');
var dbConnect = require('dbconfig.js');

var myDetails = undefined;

  var putRequest = function() {
    frisby.create('Put update contact details - required values')
      .put(url.myAccount, {
        addressLine1: 'String',
        addressTown: 'String',
        addressCounty: 'String'
      }, {json: true})
      .expectStatus(200)
      .expectHeaderContains('content-type', 'application/json')
      .auth(auth.username, auth.password)
    .toss();
  }

  var retrieveAccount = function() {
    oracledb.getConnection(
      {
        user          : dbConnect.user,
        password      : dbConnect.password,
        connectString : dbConnect.connectString
      },
      function(err, connection)
      {
        if (err) {
          console.error(err.message);
          return;
        }

        connection.execute(
          "SELECT addressLine1, addressTown, addressCounty "
          + "FROM accounts "
          + "WHERE account_id = 1",

          function(err, result)
          {
            if (err) {
              console.error(err.message);
              return;
            }
            myDetails = JSON.stringify(result.rows);
            myDetails = JSON.parse(myDetails);
        });
    });
  }

  var matchValues = function() {
    frisby.create('Match Database and API Values')
      .get(url.myAccount)
      .expectStatus(200)
      .expectHeaderContains('content-type', 'application/json')
      .auth(auth.username1, auth.password1)
      .afterJSON(function (body) {
        expect(body.addressLine1).toMatch(myDetails[0][0])
        expect(body.addressCounty).toMatch(myDetails[0][1])
        expect(body.addressTown).toMatch(myDetails[0][0])
      })
    .toss();
  }

  function Promise(fn) {
    var state = 'pending';
    var value;
    var deferred = null;

    function resolve(newValue) {
      value = newValue;
      state = 'resolved';

      if(deferred) {
        handle(deferred);
      }
    }

    function handle(handler) {
      if(state === 'pending') {
        deferred = handler;
        return;
      }

      if(!handler.onResolved) {
        handler.resolve(value);
        return;
      }

      var ret = handler.onResolved(value);
      handler.resolve(ret);
    }

    this.then = function(onResolved) {
      return new Promise(function(resolve) {
        handle({
          onResolved: onResolved,
          resolve: resolve
        });
      });
    };

    fn(resolve);
  }

  function sendRequest() {
    return new Promise(function(resolve){
      var value = putRequest();
      resolve(value);
    });
  }

  function readDatabase() {
    return new Promise(function(resolve){
      var value = retrieveAccount();
      resolve(value);
    });
  }

  function getAccount() {
    return new Promise(function(resolve){
      var value = matchValues();
      resolve(value);
    });
  }

sendRequest()
  .then(readDatabase)
  .then(getAccount);

Source: (StackOverflow)

Using a authentication login a a parameter in requesy header in frisby

I'm trying to a test that requires an authentication token login using frisby, the problem is: the response of my request is a string and not a JSON and i still havent figured out how to get it working.

I've read a few examples that i found googling but they havent been helpful so far.

Here's my code:

var frisby= require('frisby');

frisby.create('Login')
    .post('http://mid.dev.psafe.com/My.API/security/Authentication.svc/Login',
        {"user":"115303640577606155760"},
        {json:true},
        { headers: { 'Content-Type': 'application/json' }})
    .expectStatus(200)
    .afterJSON(function (token) {
        frisby.globalSetup({
            request: {
                headers: { 'User-Token': token }
            }
        });

        frisby.create('List associated devices')
            .post('http://mid.dev.psafe.com/My.API/APIAdmin.svc/GetDevices',
                {json:true})
            .expectStatus(200)
        .toss();
    })

.toss();

Here's what i got when ran the test:

1) Frisby Test: Login 
    [ POST http://mid.dev.psafe.com/My.API/security/Authentication.svc/Login ]
   Message:
     Error: Error parsing JSON string: Unexpected token q
    Given: qO1DkNvKlCaOmNXsrmvGgfIqeCQEztKJHnizItWyfKaXD9H1bwm1eTIgiINCw5Dz0
   Stacktrace:
     Error: Error parsing JSON string: Unexpected token q
    Given: qO1DkNvKlCaOmNXsrmvGgfIqeCQEztKJHnizItWyfKaXD9H1bwm1eTIgiINCw5Dz0
    at _jsonParse (/usr/lib/node_modules/frisby/lib/frisby.js:1219:11)
    at Frisby.<anonymous>     (/usr/lib/node_modules/frisby/lib/frisby.js:950:20)
    at null.<anonymous> (/usr/lib/node_modules/frisby/lib/frisby.js:1112:18)
    at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)

Finished in 0.255 seconds
1 test, 2 assertions, 1 failure, 0 skipped

Thanks!


Source: (StackOverflow)

In NODE js - accessing variable from one file in another file without html

I have one var URL = 'http://something'; in test.js I want to access to this var in another main.js file and for ex. have var MEU =URL+ '/sss';. How can I do that?

I want to export this var URL from some file in my main file, but still give me it is not declared message. Please help me with full path example, or something like "export" (which I can't use because it is reserved word)

Don't use HTML.


Source: (StackOverflow)

jsonparse fails with frisby, serializer option

I'm using frisbyjs to test an endpoint and my call looks like this:

frisby.create("POST book")
.post(apiUrl + "/book", {
    name: name,
    description: description
}, { json: true })
.inspectJSON()
.inspectHeaders()
.expectHeaderContains("Content-Type", "application/json")
.expectJSONTypes({
    id: Number,
    name: String,
    description: String
})
.expectJSON({
    name: name,
    description: description
})
.afterJSON(function (response) {
    console.log("my response");
    console.log(response);
}).toss();

My test passes and I get this in my response:

my response
{ id: 50, name: 'Test Book Name', description: 'Test Description' }

This doesn't look like proper json to me and when I try to make a GET request or use this data in afterJSON, I get parsing errors. I'm wondering why the values are not wrapped properly in double quotes ("). If I hit this endpoint in Chrome/Postman, the values are wrapped properly with double quotes. Is there a serializer option in frisbyjs?


Source: (StackOverflow)

Is possible to generate a code coverage report with Istanbul using Frisby?

I'm trying to generate a code coverage report using istanbul. Works fine with jasmine tests, but not with Frisby (jasmine-node) tests. Is a way to generate code coveraeg from frisby tests ?


Source: (StackOverflow)

frisby and read the response header with json response REST API

I am using frisby to automate the REST API testing. All of my REST API is based on json and return json response. In one of the requirement, I need to read the response header and fetch the response header and set it for next request. With json response, I am not able to read the response header. Following is sample code for my test.

frisby.create("Check to make sure that user does exist")
                                            .get(hostURL + "/api/users/checkusername/" + username, user, {json: true}, {headers: {'Content-Type': 'application/json'}})
                                            .expectHeaderContains('content-type', 'application/json')
                                            .afterJSON(function (response) {
                                            //How to read session id from header
                                                //var sessionId = res.headers[constants.SESSION_ID_HEADER_KEY]; 
                                                var exist = response.exist;
                                                expect(exist).toBe(true);

                                                });

Please help.


Source: (StackOverflow)

Get method of frisby does not work with https

I am new to frisby test. today i found I can't access https://ip address from friby api

for example:

frisby.create('my test').get("https://199.59.148.20")
output: connect error

frisby.create('my test').get("https://api.twitter.com")
this one works

please advise!


Source: (StackOverflow)

Frisby.js Error: tunneling socket could not be established

I am trying to test an REST API on my local machine using frisby.js . It throws the following error.

Error: tunneling socket could not be established.

The machine address is something like 'https://machine_name:8443'


Source: (StackOverflow)