Confirm that the dependency has been invoked using Sinon

I am currently working on testing whether a dependency has been called or not.

Here is an example of my code:

export default class vehicle {
private builder: CarBuilder;

constructor() {
  this.builder = CreateCar(); <- factory return fake data
}

createBmw(model) {
  return this.builder.validate(model); <- test this line has been called
}

This is what my test looks like:

it("should verify that the createBmw method calls validate", () => {
  //Am I doing this correctly?
  const carBuilder = new carBuilder();
  const builder = sinon.stub(carBuilder, "validate");

  const sut = new vehicle();
  sut.createBmw("5 series");

  expect(builder).to.be.called;
});

Answer №1

Sinon is unable to stub standalone functions such as the CreateCar factory function in this scenario. Therefore, it is recommended to utilize Link Seams for this purpose. To achieve this, we will employ proxyquire to create our seams.

For example:

vehicle.ts:

import { CarBuilder, CreateCar } from './builders/carBuilder';

export default class Vehicle {
  private builder: CarBuilder;

  constructor() {
    this.builder = CreateCar();
  }

  createBmw(model) {
    return this.builder.validate(model);
  }
}

builders/carBuilder.ts:

export interface CarBuilder {
  validate(model): void;
}

export function CreateCar(): CarBuilder {
  return { validate(model) {} };
}

vehicle.test.ts:

import proxyquire from 'proxyquire';
import sinon from 'sinon';

describe('68197110', () => {
  it('should pass', () => {
    const carStub = { validate: sinon.stub() };
    const CreateCarStub = sinon.stub().returns(carStub);
    const Vehicle = proxyquire('./vehicle', {
      './builders/carBuilder': {
        CreateCar: CreateCarStub,
      },
    }).default;
    const sut = new Vehicle();
    sut.createBmw('5 series');
    sinon.assert.calledWithExactly(carStub.validate, '5 series');
  });
});

Unit test results:

  68197110
    ✓ should pass (1481ms)


  1 passing (1s)

-------------------|---------|----------|---------|---------|-------------------
File               | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------------|---------|----------|---------|---------|-------------------
All files          |   83.33 |      100 |      50 |   83.33 |                   
 68197110          |     100 |      100 |     100 |     100 |                   
  vehicle.ts       |     100 |      100 |     100 |     100 |                   
 68197110/builders |      50 |      100 |        0|      50 |                   
  carBuilder.ts    |      50 |      100 |        0|      50 | 6                 
-------------------|---------|----------|---------|---------|-------------------

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

Angular - a simple method to determine the number of non-empty inputs in a complex template-driven form

As I work on multiple substantial Angular 11 template forms containing basic inputs like text, radiolists, and checkboxes, I am looking for the most effective method to calculate the percentage of completed inputs while the user is actively engaging with ...

Encountered an issue when attempting to establish a connection with the REST

I am encountering an issue with connecting to a web service deployed on an Apache server using Jersey. The error message I receive is: Failed to load http://192.168.1.200:8199/CheckinnWeb/webapi/myresource/query: No 'Access-Control-Allow-Origin' ...

What is the best way to integrate Tawk.to into a React application while using typescript?

Having some issues integrating tawk.to into my website built with React and TypeScript. I have installed their official npm package, but encountered an error message: import TawkMessengerReact from '@tawk.to/tawk-messenger-react'; Could not fin ...

hiding html elements by using the display property set to none instead of physically removing

I am currently utilizing an if-else statement to display different HTML structures. As a result, the entire HTML is being rendered twice. Is there a way we can utilize 'display: none' instead? I attempted to use it in th ...

The Java value is not returned by the Observable<boolean> stream

I'm currently working on making a request to the backend for a boolean value using observables, but I'm struggling to figure out the best approach between .map and .subscribe. return this.http.put({url}, credentials, this.requestOptions) .ca ...

unable to locate the custom npm package within my service

There is a similar inquiry posted here: My custom NPM Package is not found, but unfortunately, the solution provided did not fix my issue. I am encountering an error stating: "Could not find a declaration file for module '@dc_microurb/common' ...

Step-by-step guide for importing a JSON file in React typescript using Template literal

I am facing an error while using a Template literal in React TypeScript to import a JSON file. export interface IData { BASE_PRICE: number; TIER: string; LIST_PRICE_MIN: number; LIST_PRICE_MAX: number; DISCOUNT_PART_NUM: Discout; } type Discoun ...

In Next.js, the switch button remains in the same state even after the page is refreshed

Is there a solution for this issue? I am currently developing a switch button for a configuration page. The problem arises when I toggle the switch from active to maintenance mode, save it successfully, but upon refreshing the page, the switch reverts back ...

Ways to verify the identity of a user using an external authentication service

One of my microservices deals with user login and registration. Upon making a request to localhost:8080 with the body { "username": "test", "password":"test"}, I receive an authentication token like this: { "tok ...

Using Angular 5+ to fetch information from an ASP.NET Core Web API

Having trouble retrieving data from an ASP.NET Core 2.0 Web API with Angular 5+. The steps taken so far are as follows: An ASP.NET Core 2.0 Web API was created and deployed on a server. Data can be successfully retrieved using Postman or Swagger. Using ...

Methods for adding a new object to an array in Angular: Explained

How can I insert a new object in Angular? Here is the current data: data = [ { title: 'Book1' }, { title: 'Book2' }, { title: 'Book3' }, { title: 'Book4' } ] I would like to update the obje ...

Tips for preventing the ngbTypeahead input field from automatically opening when focused until all data is fully mapped

When clicking on the input field, I want the typeahead feature to display the first 5 results. I have created a solution based on the ngbTypeahead documentation. app.component.html <div class="form-group g-0 mb-3"> <input id="typ ...

Troubleshooting: NextJS Typescript getInitialProps returning null value

I am currently working with NextJS 'latest' and TypeScript to extract the token from the URL, but I am encountering an issue where it returns undefined. To achieve this, I am utilizing the getInitialProps method. The URL in question looks like th ...

I'm having trouble viewing the unique Google Map design on my application

I have recently customized Google maps following the guidelines in this documentation: https://developers.google.com/maps/documentation/javascript/styling For styling, I utilized the Cloud tool and opted for the available template instead of using JSON st ...

Transforming Excel data into JSON format using ReactJS

Currently, I am in the process of converting an imported Excel file to JSON within ReactJS. While attempting to achieve this task, I have encountered some challenges using the npm XLSX package to convert the Excel data into the required JSON format. Any as ...

Obtain the content of a clicked item on the following page using NextJs

I am currently working on a nextjs app that displays a list of 10 movies on the homepage, each with a Button / Link that leads to a specific page for that movie where all its content is shown. Initially, I tried adding the movie id to the Link like this: ...

Issue with Angular: ngForm object does not capture selected option

Revise to clean up unnecessary code. Having trouble displaying the selected option when I print the form object to the console. It's showing as undefined. Any guidance on what might be wrong with this code would be appreciated. Let me know if more in ...

Transferring Cookies through FETCH API using a GET method from the client-side to the server-side

Struggling with a challenge here: Attempting to send a cookie via a GET request to determine if the user is logged in. The cookie is successfully transmitted to my browser and is visible in the developer tools. When I manually make a request through the UR ...

Mastering the art of accessing properties in typescript post implementing Object.defineProperty

I was experimenting with the TypeScript playground trying to figure out decorators and encountered some questions. class PathInfo { functionName: string; httpPath: string; httpMethod: string; constructor(functionName: string, httpPath: str ...

Tips on displaying the entire text when hovering over it

I'm facing an issue with a select element that retrieves options from an API. The problem is that some options are too large for the text box and get cut off, making them hard to read for users. <div class="form-group my-4"> <lab ...