Exploring the World of Unit Testing with Jasmine and Sinon Factories

At my factory, I have implemented a getter and setter function

.factory('myService', function() {
  var car = null;
  return {
    car: car,
    get: function get() {
      return car;
    },
    set: function set(newCar) {
      car = newCar;
    }
  };
});

While writing tests for this functionality, I am facing an issue where the set method does not seem to update the value of car as expected.

myService.set = sinon.spy();
myService.get = sinon.spy()

it('should set car to new car', function () {
  var newCar = ['a','b','c'];
  expect(myService.car).toEqual(null); //pass

  myService.set(newCar);

  dump(myService.car); //null

  expect(myService.set).toHaveBeenCalledWith(newCar);//pass

  expect(myService.get).toHaveReturned(newCar);//fail

});

Can anyone provide some insights on what mistake I might be making in this scenario?

Answer №1

There are multiple issues at play here.

Firstly, the .car property is set to null initially and never gets updated, leading to a perpetual state of null:

var car = null;
return {
  car: car,
  get: function get() {
    return car;
  },
  set: function set(newCar) {
    car = newCar;
  }
};

An alternative approach could be initializing car as null within the object itself:

return {
  car: null,
  get: function get() {
    return this.car;
  },
  set: function set(newCar) {
    this.car = newCar;
  }
};

However, using this in this context may lead to potential complications down the line. Furthermore, it's puzzling why you're exposing car when you already have a getter for it.

Additionally, by replacing the original get and set functions with Sinon spies like so:

myService.set = sinon.spy();
myService.get = sinon.spy();

You lose access to the original get and set functionalities. Instead, consider wrapping the functions with Sinon spies without losing their original behaviors:

sinon.spy(myService, 'set');

This way, Sinon can spy on the functions while preserving their functionality. For more information, refer to the Sinon documentation.

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

Ways to effectively go through local storage using a loop

I'm currently working on enhancing my navbar by adding links based on searches made by users and their favorite selections. My goal is to avoid duplicate entries in the "past searched" section if the current search already exists in the list. I'm ...

Using Page.ResolveClientUrl in JavaScript or jQuery allows for easy resolution of client

I find myself in a predicament where I need to choose between using an HTML page instead of a .aspx page for performance reasons. Currently, I am using an aspx page solely because of the CSS and javascript file paths like: <script type="text/javascript ...

When executing a JavaScript program, an error with the message 'MODULE_NOT_FOUND' appeared, causing the internal module loader in Node to throw an error at line 1145

node:internal/modules/cjs/loader:1145 throw err; ^ Error: Module 'C:\Users\sande\3D Objects\JavaScript-Lesson\lesson08.js' not found at Module._resolveFilename (node:internal/modules/cjs/loader:1142:15) at Mo ...

Align the rotation of Object3D at the tab level

Seeking assistance, I am attempting to synchronize the rotation of an object loaded in the active browser tab with another object loaded in a second tab. The idea is that when the Object in the active browser tab rotates, it will send a message to the Obj ...

Looping through a series of JavaScript objects in a JSON

I've encountered an issue when trying to run a loop with a JSON query inside it. Here's what my code looks like: for (var i = 0; i < numitems; i++) { var currentitem = items[i]; $.getJSON("http://localhost/items.php", {'itemname&ap ...

Unchanging Dive Field

I'm having trouble understanding why this field isn't updating with the correct number. It seems that any value less than 1 is being rounded in the alert() function. I believe all numbers are simply getting rounded down, but I'm unsure of an ...

I need to prevent form submission when the submit button is clicked. How can I achieve this?

I'm currently developing a web application using ASP.net. Within the form, there is a submit button that has the following code: <input type='submit' value='submit request' onclick='btnClick();'>. The desired func ...

Angular-Formly facing problems with promise handling in UI Bootstrap's typeahead

I am currently using angular-formly in conjunction with integrated ui bootstrap typeahead to make a query to an api through a service. The promises were successfully resolved, however the typeahead list only displays data from the most recent input query. ...

Trouble locating DOM element in Angular's ngAfterViewInit()

Currently, I am attempting to target a specific menu item element within my navigation that has an active class applied to it. This is in order to implement some customized animations. export class NavComponent implements AfterViewInit { @ViewChild(&a ...

In Bootstrap 5, clicking inside a dropdown should not cause it to open or close unexpectedly

Check out the code snippet below: <html> <head> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d1f1212090e090f1c0d3d48534e534e">[email protected]</a>/d ...

Obtain the Key with the Greatest Value from a JSON Object

I'm currently working with data fetched from an API response in an attempt to identify the pitch with the highest speed. Below is a snippet from the API response. { page: 1, total_pages: 4, listings: [ { name: "Zack Greinke", pitc ...

The issue I'm facing with my webpack-build is the exclusive appearance of the "error" that

Hey everyone! I'm currently facing an issue with importing a module called _module_name_ into my React project, specifically a TypeScript project named react-app. The module was actually developed by me and it's published on npm. When trying to i ...

beforeunload event confirmation prompt

I am currently working with Laravel and Vue.js to create a multi-step wizard. Within this wizard, I have implemented the onbeforeunload event to prevent any unwanted actions by displaying a confirmation message. However, I am encountering an issue where th ...

Leveraging API data within React: A step-by-step guide

I have a React application where I am making API calls. To manage these calls, I created a separate file called dataService.js to contain all the functions for interacting with the API. However, when trying to log the data in my component, I am getting a ...

What is the best way to ensure a function returning a promise works effectively within a forEach loop?

Are you facing challenges using a function that returns a promise inside a forEach loop due to the asynchronous nature of the function? It seems like the forEach loop completes before the promise can finish fetching or manipulating the data. Below is a co ...

Utilizing AJAX for remote execution of JavaScript code

Suppose there is a JavaScript page located at myaddress/service.js on a server. The code in this .js file looks something like: nsBob = { a: function(someParam) {...perform actions and return result}, b: function() {...perform actions and return result} ...

An easy guide to dynamically assigning a property using jQuery

I am currently utilizing the toastr plugin and I would like to dynamically set the options using a JSON object that is retrieved from an AJAX call. I am encountering some difficulties in setting the options property and value programmatically. Below is a s ...

Providing UI field attributes within server JSON data

Suppose I have numerous form fields that need to be displayed on the user interface. Additionally, in a standard Modify workflow, let's assume that these fields will have various attributes like value, mandatory, editable, disabled, label, regex (for ...

"Implementing a sorting feature in a product filtering system with JavaScript/Vue, allowing

I have a dataset structured like this: > Price : ["800000","989000","780000","349000"] If the user selects 'sort by lowest price', I want the data to be arranged from the lowest price to the highest price as follows: > Price : ["349000" ...

Tracking your daily nutrition using cronometer with the powerful combination of JavaScript

I'm currently developing a JavaScript cronometer in vueJS. I want the timer to start at 5 minutes (300 seconds) and then continue counting minutes and seconds. Although my cronometer is functioning, I am struggling to get it to start counting minutes ...