Squire.js failing to replace mock dependency while utilizing store

Exploring Squire.js as a dependency loader for RequireJS. Testing in a standard web browser environment to run unit tests. Attempting to utilize store to access my mocks, but struggling with preventing Squire from loading the actual module.

The usage of mock functions smoothly:

define(['lib/squire'], function (squire) {
    var injector = new squire();

    injector
    .mock('modules/dependency', {
        run: function () {
            console.log("fake dependency run");
        }
    })
    .require(['modules/module-under-test'], function (module) {
        module.run();
    });
});

Console output:

module under test loaded       module-under-test.js:2
module under test run          module-under-test.js:5
fake module run                module-test.js:8

However, encountering an issue when trying to use store like so:

define(['lib/squire'], function (squire) {
    var injector = new squire();

    injector
    .store('modules/dependency')
    .require(['modules/module-under-test', 'mocks'], function (module, mocks) {
        mocks.store["modules/dependency"] = {
            run: function () {
                console.log("fake dependency run");
            }
        };
        module.run();
    });
});

The actual module is being used and executed:

real dependency loaded      dependency.js:2
module under test loaded    module-under-test.js:2
module under test run       module-under-test.js:5
real dependency run         dependency.js:5

Squire documentation explicitly states that this should work fine. Using the latest versions of Squire.js from Github and RequireJS from requirejs.org. What could be the mistake on my end?

Answer №1

In the second example, it seems like you may have missed calling the run method. Assuming it should be called after assigning to mocks.store["modules/dependency"].

The issue could be that you are trying to stub the entire dependency instead of just the run method. This works in the first scenario because the dependency hasn't been resolved yet. However, in the second case, the module-under-test already has a reference to the dependency, so replacing it in Squire's store doesn't have an effect. The correct way to use store would be:

mocks.store["modules/dependency"].run = function () {
    console.log("fake dependency run");
};

If you need to replace the whole dependency, then using mock is the right approach. Store allows you to stub individual properties before they are accessed by the code under test. If the code loads the property upon initialization, you'll still need to use mock.

An alternative solution is to require the dependency along with Squire and stub only the necessary methods. Then, use mock to make Squire resolve dependencies with your partially stubbed dependency for the module under test. Here's how you can do it:

define(['lib/squire', 'modules/dependency'], function (squire, dep) {
    var injector = new squire();

    dep.run = function () {
        console.log("fake dependency run");
    };

    injector
    .mock('modules/dependency', dep)
    .require(['modules/module-under-test'], function (module) {
        module.run();
    });
});

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

A dynamic modal window built with ReactJS

I am struggling to understand how to make my app function properly. There is a component called ContactAdd that should render the component ModalWindow when clicked. The ModalWindow component requires a parameter called isOpened={this.state.open}. How c ...

Is it necessary to include my library dependencies in the devDependencies section if I am only planning to publish the library bundle?

When creating a bundle for a library, should the library dependencies be placed in devDependencies? I am developing an NPM library in TypeScript that relies on several dependencies, including React components. As part of the build process, we compile to J ...

Why isn't CSS showing up in preview mode on the network tab?

I have been using nextjs for server-side rendering and I am encountering an issue where my CSS class is not being applied on the preview tab, it only works on the client side. Any idea why this is happening? Here is the code snippet: https://codesandbox.io ...

Modifying an element in an array while preserving its original position

Currently, I am working on updating the state based on new information passed through response.payload. Here is my existing code snippet: if(response.events.includes('databases.*.collections.*.documents.*.update')) { setMemos(prevState => pre ...

How to Use JQuery to Retrieve the Nearest TD Element's Text Content

Hey there, here is some HTML code that I need help with: <tbody> <tr> <td class="text-center"><input type="text" class="form-control cardSerialNumber"></td> <td class="text-center"><button type="button" onc ...

What is the best way to incorporate auto refresh in a client-side application using vue.js?

Disclaimer: I have separated my client application (Vue.js) from the server side (DjangoRest). I am utilizing JWT for validating each request sent from the client to the server. Here is how it works - The client forwards user credentials to the server, an ...

Releasing the mouse button after dragging successfully without the use of any libraries

I have implemented a pure CSS snap scroll feature and now I need to determine the position of an element in relation to the viewport once the user stops dragging. However, I prefer not to rely on any complex libraries as I do not require any actual movemen ...

Guide to placing a button on the same line as text with the use of JavaScript

Does anyone know how to add a button to the right of text that was added using JS DOM? I've tried multiple techniques but can't seem to get it right - the button always ends up on the next line. Any tips on how to achieve this? var text = docu ...

``The error 'Uncaught SyntaxError' is thrown during the production build of

I am facing an issue with the production build of my Vuejs application. When I use the npm run build command to generate the production build and then use serve -s dist to deploy it, everything works fine except for one parameterized path (product) in Vue ...

Is there a more efficient algorithm available to solve this problem in a quicker manner?

I'm currently working on iterating through the body tag and all of its nested children. I want to be able to access each child, even if they contain additional children within them. Can anyone offer a more efficient algorithm than the one I came up wi ...

Generating dynamic JSON objects in Node.js

Here is the initial JSON data I have: { "fullName": "abc", "age": 19, ... } I am looking to utilize Node.js in order to add elements from the above JSON to an object called Variables within the following JSON: { &q ...

Ways to retrieve data from response instead of subscription JSON in Angular 2/4

My Service : retrieveData(url,request) { return this.http.post(this.apiUrl+url,request).subscribe( (response) => {return response.json()} ); } My Component : ngOnInit() { this.data = this.dataService.retrieveData(&apos ...

Sort various divs using a list

I have multiple divs containing different content. On the left side, there is a list of various categories. When a category is clicked, I want to display the corresponding div for that category. Initially, I want the main category to be loaded, with no opt ...

issue with visibility of checkbox in material ui table row

In a separate file called TradesTable.js, I have created a table using Material UI for my React app. const DummyTableRow = (props) => { let myRows = props.trades.map((trade, index) => { return <TableRow> <TableRowColumn ...

Tips for transferring state value from a form to a child modal

As a newcomer to React, I am uncertain about the best approach to take in my project. Specifically, I have a modal component that should appear once the user fills out a form and clicks on the Preview Voucher button to display the entered values. Below, yo ...

Leverage the power of ssh2-promise in NodeJS to run Linux commands on a remote server

When attempting to run the command yum install <package_name> on a remote Linux server using the ssh2-promise package, I encountered an issue where I couldn't retrieve the response from the command for further processing and validation. I' ...

Look for identical values within a nested array

My data consists of a nested array where each element has a property called name, which can only be either A or B. I need to compare all elements and determine if they are all either A or B. Here is an example of the input: [ { "arr": { "teach ...

Have you ever encountered the frustration of being unable to navigate to the next page even after successfully logging in due to issues

I'm currently utilizing Vue and Firebase to build my application. One of the features I want to implement is the redirect method using vue-router. Within my vue-router code, I've included meta: { requiresAuth: true } in multiple pages as middlew ...

Transfer information from an Express route to a function exported from a Node module

I'm new to using node.js and I've been told that I need to use middleware, but I'm having trouble understanding its purpose and the proper way to implement it. I have data that is being sent from my view to an express route. ROUTE - route.j ...

Perform an ajax request to check for the existence of an image and insert

I've been trying to implement asynchronous JavaScript based on guidance from this answer, but I'm facing some difficulties in understanding where things are going wrong. My goal is to use autocomplete functionality to request specific files from ...