Having trouble injecting $resource into my Jasmine unit test

I've encountered an issue while trying to test my self-written service that utilizes $resource. I'm facing difficulties when trying to inject $resource into my test spec.

My setup includes Typescript with AngularJS 1.6.x, and here is a snippet of my service class:

export class MyDataService {

  constructor(
    private $resource: ng.resource.IResourceService
    ) {
    this.someResource = $resource('api/some-endpoint');
  }

  public getThings() {
    return this.someResource.get().$promise;
  }
}

Below is my test spec using Jasmine + Karma:

import { MyDataService } from './my-data-service.service';

describe('MyDataService Tests:', function() {
  let myDataService: MyDataService;
  let $resource: ng.resource.IResourceService;
  let resourceSpy: jasmine.Spy;

  beforeEach(inject(function(_$resource_){
    $resource = _$resource_;
    myDataService = new MyDataService($resource);
    resourceSpy = spyOn(myDataService.resource, 'get');
  }));
  afterEach(function() {
    resourceSpy.calls.reset();
  });

  describe('when calling getThings', function() {
    it('should call get on the underlying resource instance', function() {
      myDataService.getThings(1, 15);
      expect(resourceSpy).toHaveBeenCalled();
    });
  });

The error message

Unknown provider: $resourceProvider <- $resource
keeps popping up, even though angular-resource is correctly included in my Karma config.

I'm also using angular-mocks with Karma. Could the reason for this error be that $resource isn't part of the mocks library? I haven't specified any angular modules to load in my tests as I aim to test classes in isolation without loading an entire module.

Thank you.

Answer №1

It looks like @PetrAveryanov provided the accurate solution. It's worth mentioning that, unless there are specific camel case validations happening in OP's Jasmine and not in my version of Jest, the module name has been updated to ngResource:

beforeEach(angular.mock.module('ngResource'));

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

Perform an HTTP GET request to a RESTful service with specified parameters using Angular 2

I'm currently facing an issue while attempting to create a GET request to the YouTube Web API. I'm struggling with passing parameters through the http.get function and have confirmed the request is being sent using Fiddler. However, I keep receiv ...

What steps can be taken to initiate Nx Release on the apps/* when modifications are made to the connected libs/* modules?

Trying out the nx release command but struggling to get it to release an app when there are changes to a dependent module. Examining the graph below, you can see that I have 3 apps, with 2 depending on the shared-ui module. https://i.sstatic.net/QYDBlRnZ.p ...

The clearfix feature is ineffective when using AngularJS

<ul class="dropdown-menu wm_search_div" ng-show="searchDivShow"> <li ng-repeat="user in searchUserList"> <a href="javascript:void(0);" class="wm_clearfix3"> <img ng-src="{{user.faceIcon}}" class="pull-left wm_se ...

The functionality of Ng update is failing to operate properly on outdated node versions

Currently in the process of upgrading from angular 7 to 15 for my project. Taking it step by step, but I'm facing the challenge of having to do it manually since my ng update isn't working under any circumstances. The error message states that my ...

Angular: exploring additional challenges with dynamic filtering

I'm currently working on making dynamic filters functional and I believe I'm close to achieving it. However, it seems like the model isn't correctly passed back to the watch function. Even with the initial set of filters, it doesn't see ...

What is the process for expanding types for a section element in Typescript?

When working with TypeScript, we define our component props types by extending a div like so: import { HTMLAttributes } from "react"; export interface IContainerProps extends HTMLAttributes<HTMLDivElement> { // Additional custom props for the c ...

Retrieving the necessary data from my object to perform a sum calculation in angular

Having trouble retrieving an attribute from an array in my code. In my .ts file, I am fetching data from my backend endpoint like this: export class PostFeedComponent implements OnInit { data: any = {}; constructor(private http: HttpClient) { t ...

Mastering AngularJS - Field Population with Blinking Placeholders

I understand that AngularJS fills in fields through their model. HTML is loaded first: <input type="text" data-ng-model="data.myValue" placeholder="example"> The JavaScript code comes next: $scope.data = {}; $scope.data.myValue = 'hello my v ...

How come Angular8's routerLinkActive is applying the active class to both the Home link and other links in the navigation bar simultaneously?

Currently, I am facing an issue with routing in my project where the home tab remains active even when I click on other tabs. I have tried adding routerLinkActiveOption as a solution, but it doesn't seem to be working for me. <ul class="nav nav-ta ...

How to open a print preview in a new tab using Angular 4

Currently, I am attempting to implement print functionality in Angular 4. My goal is to have the print preview automatically open in a new tab along with the print popup window. I'm struggling to find a way to pass data from the parent window to the c ...

Unexpected patterns observed when utilizing parent/child routing files

I am working with a Node/Express backend that is implemented using TypeScript. Whenever I make changes to a file and save it, if I test the root route in Postman localhost:8000/, I receive the expected response. However, when I test localhost:8000/user af ...

Personalized data type for the Request interface in express.js

I'm attempting to modify the type of query in Express.js Request namespace. I have already tried using a custom attribute, but it seems that this approach does not work if the attribute is already declared in @types (it only works for new attributes a ...

Storing form data into a database using AngularJS: A comprehensive guide

I am relatively new to working with angular technology. Currently, I am developing an internal tool that allows me to retrieve and update user details such as location, work profile, and mobile number, among others. To achieve this, I have created a form w ...

The vast expanse of the cosmos, replacing the

When attempting to simulate pressing the ENTER key in my code, I am getting the same result as if I pressed SPACE instead. I'm not sure why this is happening. field.clear().click().sendKeys("Hello"); browser.actions().sendKeys(protractor.Key.ENTER).p ...

Typescript enables bidirectional control of Swiper

I attempted to use the two-way control slider example from Swiper documentation, but I encountered TypeScript errors that prevented it from working correctly. Is there a way to make it compatible with TypeScript? The specific errors I received were: TS23 ...

What is the correct way to add type annotations to an Axios request?

I have meticulously added type annotations to all endpoints in my API using the openapi-typescript package. Now, I am looking to apply these annotations to my Axios requests as well. Here is a snippet of code from a Vue.js project I have been developing: ...

What is the process for retrieving an Object from $cookies?

I've encountered an issue where I'm storing a user object on a Cookie and, upon the client's return visit to the site, I want to utilize this object's properties. However, upon the client's return, my cookie object appears as [obj ...

The comparison between "rxjs-tslint" and "rxjs-tslint-rules" npm packages

Previously, I utilized the rxjs-tslint-rules package to identify RxJS-related issues in my projects. This package was included in the devDependencies section of my projects' package.json files. Now, there is a new rxjs-tslint package that introduces ...

Having difficulty transferring data between components using @Input syntax

I am having trouble passing the FailedProductId from Component1 to Component2 using @Input. Below is the code snippet: export class Component1 implements OnInit { public FailedProductId="produt"; constructor(private employeeService: ProductService) {} ...

typescript error: referencing a variable before assigning a value to it in function [2454]

I am currently in the process of creating a store using nextJS I have two variables that are being assigned values from my database through a function let size: Size let ribbonTable: Ribbon async function findSizeCategory(): Promise<v ...