Utilize sinon with a vue action to create a mock class for unit testing puposes

I need to verify if my 'SIGN_IN' action is functioning correctly.

This is how my action currently looks (not the most refined implementation but it's what I have at the moment):

// actions.js

import {
  SIGN_IN, SIGN_OUT, SET_AUTH_TOKEN, CLEAR_AUTH_TOKEN, USER_AUTHORISED,
} from '@/store/types';
import AuthService from '../../../authService';

export default {
  async [SIGN_IN]({ commit, rootState }) {
    const authService = new AuthService(rootState.clientSettings);
    let response;
    try {
      response = await authService.getToken();
    } catch (e) {
      console.log('User not authorised');
    }
    if (response) {
      commit(SET_AUTH_TOKEN, response);
    } else {
      commit(USER_AUTHORISED, false);
    }
  },
  ...
};

authService.getToken(); is the method I want to mock the response of in my test. I want to be able to simulate a mock response for this in my testing scenario.

The structure of the AuthService class is as follows:

// authService.js

import { PublicClientApplication } from '@azure/msal-browser';

class AuthService {
  constructor(clientSettings) {
    // Constructor logic
  }
    ...

    async getToken() {
      // Method logic
    }

    ...
}

export default AuthService;

This is my attempted test script:

// actions.spec.js
// Testing code

During debugging, I am encountering difficulty in stubbing the response for getToken. It continues to call the actual instance of AuthService created within my action. My goal is to simply confirm that SET_AUTH_TOKEN is being called and nothing more. How can I effectively replace the entire AuthService class with a stub so that my action utilizes that one instead? Is there a more efficient way to achieve this without passing an instance of AuthService into the action itself?

Answer №1

To mock an ES6 class, you'll want to stub the prototype method like so:

sinon.stub(AuthService.prototype, 'getToken').resolves(mockResponse);

For more information, check out this article: how to mock es6 class

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

Issue with clientHeight not functioning properly with line breaks in Angular 2 application after ngAfterViewInit

I have successfully created a Gridify page in my Angular 2 application using the Gridify library. To initialize it, I've utilized a custom ngAfterViewChecked method: ngAfterViewChecked() { var selector = document.querySelector('.read-grid& ...

JavaScript - Determine the point at a specific distance between two given points

I am working with two points, referred to as p1 and p2. Is there a way for me to determine the position from p1 to p2 based on a specified length? var p1 = {x: 100, y: 400}; var p2 = {x: 300, y: 500}; var len = 40; https://i.sstatic.net/Q7pOH.png ...

Populate an HTML5 arc with an image - Leveraging the power of HTML5 Canvas

I'm working with an HTML5 Canvas (JSFiddle) that currently displays circles created using the following function: function createball(x,y,r,color){ context.beginPath(); context.arc(x,y,r,0,Math.PI*2,true); context.fillStyle = color; c ...

Adding a JavaScript script tag within a React app's ComponentDidMount - a guide

I am currently in the process of implementing Google Optimize on my website. I need to include the following script tag within my page: <script>(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date; h.end=i=function(){s.classN ...

Updating the Nuxt PWA Version

Currently, I am in the process of developing a progressive web app (PWA) using the Nuxt/PWA module. I successfully identified a change within the service worker during the installation event of Workbox: plugins/pwa-update.js export default async (context) ...

Obtaining the selected date value from a Vue.js datepicker

How can I calculate the difference in days between two selected dates in Vue.js before the form is submitted? I want to provide a price based on this calculation. I am using a Persian date picker, which you can find here: https://github.com/talkhabi/vue- ...

Show the error messages directly beneath each field

Currently, I am utilizing the package found at https://github.com/KuwaitNET/djvue. Despite this specific context, my inquiry pertains to a more general question regarding validation methods. I have crafted the following method to assess the validity of pho ...

Invoke a C# function (WebMethod) using Javascript (JQuery)

Having a function setup like this [WebMethod] public static string Hello() { return "hello"; } I am attempting to call it on my aspx page using the following approach function sendData(){ $.post("Default.aspx/Hello", ...

My website doesn't seem to support Javascript, although it works perfectly on jsfiddle

I was tinkering around on jsfiddle and managed to get my code working flawlessly. However, when I tried to copy and paste it elsewhere, the functionality broke down. It seems that for some inexplicable reason, the code doesn't seem to pass through the ...

The issue of AJAX .done() method returning undefined when using $.each() on JSON response

I am having trouble retrieving the JSON response from an $.ajax() request. After selecting a car model, I receive data from the API, but I am unable to access the JSON results to populate a new drop-down list with the required information. HTML <div cl ...

How can the total sum of values from a list of JSON objects be calculated in an HTML document?

I am currently designing an HTML form that, upon submission of a user's name, should return an integer representing the sum of all purchased items by the user. The API response is in JSON format and appears as follows: [{"Phone":800}, {"laptop":1500} ...

Storing the created .wav file on the server using PHP

Is there another way to handle this? How can I manage streaming of a WAV file? I'm currently working on a platform that allows users to create their music compositions and the system outputs a .wav file for each creation. While I can play the mus ...

How to resolve a TypeError saying "Object(...) is not a function"?

I've been attempting to display material-ui tabs as a component on another page, but I'm encountering an error that causes the code to break when loading the page with this component. I've tried two different methods of rendering this compo ...

Unidentified entity triggering an error in the console

It seemed like there wasn't anything quite like this before... at least not that I could understand with my limited experience. I was experimenting with creating a global object that contains methods, including instructions for handling AJAX requests ...

Looping through arrays using ng-repeat

{ "employees" : [ { "name" : "XXX", "id" : "1", "Salary" : [ { "Month" : "XXXX", "Amount" : "XXXX", }, { "Month" : "XXXX", "A ...

Lack of y data in the Highcharts

I am facing an issue with retrieving yAxis data in Highcharts. You can view the fiddle at https://jsfiddle.net/LLExL/6496/. I have loaded Highcharts using the code below. $(function () { $('#RankingReportsHistory').highcharts( ...

Switch input trigger for immediate page refresh rather than standard input clearing

I want to customize how the clear input option functions. Normally, when you click on the X clear button, it clears the search input field. Instead of clearing the search input, I would like the clear button to trigger a page reload. This is the X button ...

What is the best way to showcase a div on top of all other elements in an HTML page?

As a newcomer to html and css, I have successfully created a div that contains city names. The issue I am currently facing is when I click on a button to display the div, it gets hidden behind the next section of my page. Take a look at the image below for ...

The position of the legend in Amchart remains unchanged

Dealing with the issue of chart size when there is a large legend can be challenging. I came across an article that addresses this problem: Putting a legend outside the chart area. However, the downside to this solution is that it restricts placing the leg ...

Unspecified type for 'props' parameter - a hurdle in Vue 2's composition API

I've hit a roadblock while attempting to integrate TypeScript into an existing Vue 2.6 project. Unfortunately, I'm required to stick with version 2.6 for legacy reasons. I've gone ahead and installed the composition API as a plugin. The err ...