Unit Testing in Aurelia: Creating a Mock for a Custom Resolver

Below is the snippet of code that I am currently trying to test:

import {inject} from 'aurelia-framework';
import {CrudResource, DependencyFactory} from 'utils';

let commonData = {};
    @inject(DependencyFactory.of(CrudResource))
    export class CommonDataCache {
        constructor(crudResourceFactory) {
            this.crudResource = crudResourceFactory('/Common');
        }
        data() {
            return Object.keys(commonData).length > 0 ? commonData :
                this.crudResource.get().then(response => {
                    commonData.clientEntities = response;
                    return commonData;
                });
        }
    }

The focus now shifts towards the testing aspect (only essential parts have been included for conciseness):

beforeEach(() => {
        container = new Container();

        container.registerInstance('DependencyFactory.of(CrudResource)', new CrudResourceFactoryMock());

        templatingEngine = container.get(TemplatingEngine);

        cdc = templatingEngine.createViewModelForUnitTest(CommonDataCache);
    });

In essence, my objective is to provide a mocked factory when injecting the resource (the factory enables configuring the injected dependency upon instantiation), in order to pass in a mocked dependency. The hurdle I'm encountering is that despite registering a mocked factory for the resolution of

'DependencyFactory.of(CrudResource)'
, the CommonDataCache class seems to be instantiated with its original dependency instead of the mocked one. It appears that aurelia is not recognizing that a mocked factory has been registered.

Your help and insights are greatly appreciated.

Answer №1

Personally, I tend to avoid incorporating Dependency injection in my Unit Tests. Instead, I prefer to generate a mock object and provide that as an argument to the constructor for CommonDataCache.

By introducing DI into the testing process, you shift away from true Unit Testing and veer more towards End-to-End (E2E) testing.

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

When using WYSIWYG editors, be on the lookout for empty paragraphs and incorrect code in CSS, JavaScript, and

I am currently in the process of redesigning a website for a client. The site is already built using Joomla 1.7, but I am facing an issue with the articles section that was created by the client using a WYSIWYG editor. The problem lies in the messy code st ...

The properties of a JSON object are not explicitly defined

When I make an AJAX call, I receive a JSON object and log it using this code: console.log(response); This is the response that gets logged in the console: {"filename":"new.jpg","orientation":"vertical"} However, when I try to access the orientation pro ...

Having trouble with using findByIdAndUpdate and push in MongoDB?

As someone who is new to Mongodb, I have been using the findByIdAndUpdate function to update a document in my project. However, I noticed that it returns the old document instead of the updated one. Below is the code snippet of my function: exports.crea ...

Encountering issues with fs.writeFile function in a freshly set up Vue project

After initializing a new Vue project with vue cli, I encountered an error when attempting to write files in the main.js file. Below is the code snippet that caused the issue: const fs = require('fs'); // Data to be written to the file. let dat ...

Finding the Client's Private IP Address in React or Node.js: A Comprehensive Guide

Issue I am currently facing the challenge of comparing the user's private IP with the certificate's IP. Is there a method available to retrieve the user's private IP in react or node? Attempted Solution After attempting to find the user&a ...

Sorting prices in descending order using Expedia API

Is there a way to arrange prices in descending order using the response.hotelList[i].lowRate? The provided code is as follows: success: function (response) { var bil = 1; var hotel_size = response.hotelList.length; $('#listD ...

Retrieving checkbox data and transmitting it without using a form submission

I've been attempting to extract values from a checkbox group, but for some reason, it's not working as expected. Here is the approach I'm taking: Using a loop to generate checkboxes <input class="group1" type="checkbox" name="catCheck" ...

What is the most effective method to implement an isLoggedIn function in AngularJS that is accessible from any controller or template?

I'm looking to create an isLoggedIn() function that can be accessed by both controllers and templates. Templates need this function to execute something like ng-show="isLoggedIn()". What would be the most efficient way to achieve this? If using a ser ...

Tips for extracting the chosen value from a dropdown list within a table cell using JavaScript

Here is an example of an HTML element: <td> <select> <option value="Polygon 47">Polygon 47</option> <option value="Polygon 49">Polygon 49</option> </select> </td> I am looking for a ...

Organizing JSON keys based on their values using Typescript

In the context of a main JSON structure represented below, I am interested in creating two separate JSONs based on the ID and Hobby values. x = [ {id: "1", hobby: "videogames"}, {id: "1", hobby: "chess"}, {id: "2", hobby: "chess ...

The content within Contentful is presented in a JSON object format, but accessing specific values is proving to be

I have successfully added two records in the contentful database and now I am attempting to fetch the content from Contentful into my React-hooks website. However, I am facing difficulties retrieving the values for title, description, image, and shortDescr ...

What steps can be taken to eliminate the useSearchParams() and Suspense deployment error?

I'm encountering an issue where ⨯ useSearchParams() needs to be enclosed within a suspense boundary on the page "/PaymentPage". More information can be found at: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout Although I have wra ...

Customize the element of the root node of a MUI component using the styled()

I am trying to implement the "component" prop with a MUI component (such as ListItem) using the styled() API. However, I am facing an issue where it says that "component" is not a valid prop. Can someone guide me on how to correctly achieve this? I have se ...

Fragment errors detected in the Menu Component

I am facing an issue with my code where I am getting an error in the console saying that the Component cannot receive fragments as children. How can I remove the fragments while retaining the logic? Every time I attempt to remove the fragments, I encounter ...

javascript - Convert a string into a JSON object

Looking for assistance here as I am fairly new to this. My goal is to transform the fullName string returned from a webapp UI using Selenium WebDriverIO. Here's what I have: const fullName = "Mr Jason Biggs"; The desired outcome should be structured ...

Building a High-Performance Angular 2 Application: A Comprehensive Guide from Development to

Recently, I began developing an Angular2 project using the quickstart template. My main concern now is determining which files are essential for deployment on my live server. I am unsure about the specific requirements and unnecessary files within the qu ...

Postman is showing an error when making a request using Express.js app.get()

Recently, I started working with Express.js and I am using Postman to test my API. When running the code below, I successfully retrieve all members from the object: // gets all members app.get('/api/members', (req, res) => { res.json(membe ...

Store the output of the function in a variable

Here is a script that was provided to me: <div id="container1"> <script> var script = document.createElement("script"); script.type = "text/javascript"; script.text = 'document.write(xmlDoc.getElementsByTagName("INFO") ...

Is it feasible to activate an action on a click of a Vimeo video?

Is there a way to activate an event by clicking if a video is set with background=1 and has no controls? This particular video is from Vimeo, using a plus account which allows for setting background=1. The scenario involves a Vimeo video playing on loop ...

Enhancing MEAN Stack Application by Updating Table Post Database Collection Modification

In my efforts to ensure that my table data remains synchronized with the database information, I have encountered an issue. Whenever Data Changes: $scope.changeStatus = function($event,label,status){ var target = $event.currentTarget; target ...