Experimenting with sails.socket using npm for testing purposes

Currently, I am utilizing sails.js v0.11.0 and delving into unit testing. While I have a good grasp on testing normal controllers through http requests, I am at a loss on how to approach testing the same calls via socket requests. Any recommendations for helpful resources or sample tests involving sockets would be greatly appreciated.

var assert = require('assert');
var request = require('supertest');

describe('Auth Controller', function () {

  describe('#callback()', function () {

    it ('Should successfully authenticate passport-local if email and password are valid', function (done) {

      // HTTP Request version
      request(sails.hooks.http.app)
        .post('/auth/local')
        .send({
          identifier: 'test@example.com',
          password: 'admin1234'
        })
        .expect(200)
        .end(function(err) {
          done(err);
        });

    });

    it ('Should return error code if email is invalid during passport-local authentication', function (done) {

      // HTTP Request version
      request(sails.hooks.http.app)
        .post('/auth/local')
        .send({
          identifier: 'invalid_email@example.com',
          password: 'admin1234'
        })
        .expect(403)
        .end(function(err) {
          done(err);
      });

    });

    it ('Should return error code if password is invalid during passport-local authentication', function (done) {

      // HTTP Request version
      request(sails.hooks.http.app)
        .post('/auth/local')
        .send({
          identifier: 'test@example.com',
          password: 'invalid_password'
        })
        .expect(403)
        .end(function(err) {
          done(err);
      });

    });

    // Test with Web Sockets from sails.io
    describe('sails.socket', function () {

      describe('With default settings', function() {

        describe('once connected, socket', function () {

          it ('Should successfully authenticate passport-local via web socket if email and password are valid', function (done) {

            // Socket version
            request(sails.hooks.http.app)
              .post('/auth/local')
              .send({
                identifier: 'socket_test@example.com',
                password: 'admin1234'
              })
              .expect(200)
              .end(function(err) {
                done(err);
              });

          });

          it ('Should return error code if email is invalid during passport-local authentication via web socket', function (done) {

            // Socket version
            request(sails.hooks.http.app)
              .post('/auth/local')
              .send({
                identifier: 'invalid_socket_email@example.com',
                password: 'admin1234'
              })
              .expect(403)
              .end(function(err) {
                done(err);
              });

          });

          it ('Should return error code if password is invalid during passport-local authentication via web socket', function (done) {

            // Socket version
            request(sails.hooks.http.app)
              .post('/auth/local')
              .send({
                identifier: 'socket_test@example.com',
                password: 'invalid_socket_password'
              })
              .expect(403)
              .end(function(err) {
                done(err);
            });

          });

        });

      });
    });

  });

});

Answer №1

In my exploration, I discovered that Sails provides valuable resources for understanding web sockets. While this information isn't readily available in their standard documentation, it can be found within the sails.io.js project on GitHub. Specifically, delving into their example files offers a comprehensive view of setup and teardown procedures for socket testing. For a detailed insight into the testing process itself, refer to the test files within the project repository.

Answer №2

I didn't come up with this solution originally, but in case you're here looking for the answer, here it is.

To make io a global variable in the bootstrap, do the following:

// test/boostrap.test.js

var client = require('../assets/js/dependencies/sails.io.js');

global.io = new client(require('socket.io-client'));
io.sails.url = 'http://localhost:1337/';

Then you can use them like this:

//test/callbacks.test.js
describe('socket request', function () {

 it ('passport-local authentication should succeed if email and password valid', function (done) {

  io.socket.post('/auth/local', { identifier: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd9885948e8994939ad3888e988fbd98909c94d39e9290">[email protected]</a>', password: 'admin1234' }, function (data, jwres) {
  assert.equal(jwres.statusCode, 200);
  done();  
 });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I have an inquiry regarding the live method

$('.classname').live('click',function() { some code; }); Would there be any performance issues if there are around 100 to 300 elements with this specific class? ...

What is the process for linking dynamic content to document-ready events?

When it comes to jQuery and JavaScript, I admittedly struggle a bit. I have a specific question but can't seem to find the right search terms to get me there. It involves using either .trigger() or on(), but I'm unsure of the correct implementati ...

The popup input fields of ckeditor encounter issues when combined with a bootstrap 5 modal (ckeditor version 4)

Encountered an error while using ckeditor in a bootstrap 5 modal. It seems to be a common issue with various solutions available for different bootstrap versions, but I'm struggling to find one for bootstrap 5. Could someone please take a look? Here ...

Utilizing ASP.NET AJAX: Enhancing User Experience with ScriptManagerProxy for HTML Button Click Events

I am currently working on a solution for the following issue: Managing the client-side click event of a button - preventing postback if the JavaScript call returns false (e.g. onclick="js:return IsThisAllowed()") The JavaScript method will either return ...

Ensure that nested DTO objects are validated using class validator

Currently, I am utilizing the class validator to validate incoming data which comprises an array of objects that need validation individually. An issue that has arisen is that despite inputting everything correctly, I keep encountering errors. It appears ...

Change a JavaScript object into an array with different options while still maintaining the keys

I am attempting to transform the following JavaScript object: image_uploads: [ 0: { upload_id: 50, }, 1: { upload_id: 51, }, 2: { upload_id: 52, }, ] Into separate entries using this structure for inclusion in the body of a POST r ...

Tips for translating an HTML webpage from Arabic to English

I have a bootstrap site with HTML pages but no backend functionality. How can I manually translate from Arabic to English, given that I already have the translations for all content and don't need to rely on translation tools? Is there a way to map Ar ...

The function 'ChartModule' cannot be called, as function calls are not supported

I am encountering a similar problem as discussed in Angular 2 - AOT - Calling function 'ChartModule', function calls not supported ERROR: Error encountered while resolving symbol values statically. Trying to call function 'ChartModule&apos ...

Looking for recommendations on JSON format for an AJAX response?

Suppose I submit a form through Ajax and am awaiting a response from the server: Pass/fail status If fails, a compilation of validation errors including corresponding field ids/names, etc Is there a widely adopted or recommended JSON format for organizi ...

What does 'this' refer to in a JavaScript function that is inside an object?

I'm currently working with a JavaScript code snippet that looks like the example below. On this particular line, this.orgBusinessKey = this.user.noaOrganisationList[0].businessKey; I'm wondering if the this scope will contain the user instance ...

The Angular Element's emitted number transforms into a string once it reaches the JavaScript event listener

Within my Angular Elements web component, I have defined and emitted events in the following way: @Input() groupId: number = -1; @Output('group_change') groupChange!: EventEmitter<number>; ... this.groupChange.emit(groupId); I integrated ...

Writing the success function for a jQuery ajax call involves defining the actions to be taken once

Embarking on my journey to learn jQuery and web development, I am faced with the task of sending user input (username and password through a submit button) to a PHP page using .ajax and success function. Below is the HTML form code: <form id="form1"&g ...

How can I use `app.js` in Zendesk to connect to an external API using the complete URL

As someone new to developing Zendesk apps, I've been following the step-by-step guide available here. To Summarize I'm facing an issue with passing external API URLs to the AJAX call syntax within Zendesk's app.js file. You can find my sim ...

Exploring the dichotomy between controlled and uncontrolled elements within React. The _class attribute causing unexpected changes in an un

I created a custom Checkbox component that is essentially a styled checkbox with a 'fake element' acting as the original one. Custom Checkbox Component import React, {Component} from 'react'; import FormGroup from 'react-bootstra ...

Exploring the world of two-dimensional arrays in D3 programming

I am interested in visualizing data obtained from the census data API, specifically from the ACS survey. The data is not in a typical JSON format, but rather as a two-dimensional array. It appears like this: [ [ “POPULATION”, “DATE”, ...

managing numerous outdated requests on the server

Within my application, there is a map feature that sends a request to the server whenever a user interacts with it, such as zooming in or panning. The issue arises when users perform rapid actions, leading to multiple requests being sent to the server and ...

Issue with my "message.reply" function malfunctioning in Discord.JS

I'm currently learning how to use discord.Js and I am facing an issue with my message.reply function not working as expected. I have set up an event for the bot to listen to messages, and when a message containing "hello" is sent, it should reply with ...

Ember: Utilizing Models as Data Sources for CollectionViews

I am looking to integrate model data retrieved from an ajax request into the content of an Ember.CollectionView in order to create a list of items. My goal is to display a list showing the title from each object in the array received from the API. I am cur ...

The Express API is failing to recognize the data keys that were sent from the React frontend, despite being clearly specified

I am facing an issue while trying to send data to a REST API using React hosted in a separate application. The API does not seem to receive the keys sent, even though I checked the results in Chrome and found this output:(2) ["imageSrc", File]0: "imageSrc" ...

Please be patient for 5 seconds until the download button becomes visible

While I am familiar with using javascript to accomplish this task, I am in need of a more secure method. The current setup allows anyone to simply view the page source, obtain the link, and bypass the 5-second waiting period. Does anyone have a solution f ...