Setting an Alias for AVA Tests: A Step-by-Step Guide

I need to set up global aliases in my project without using Webpack or Babel. Currently, I am testing with AVA.

The npm package module-alias allows me to define aliases in my package.json file. However, when I try to create a basic example following the documentation and setting a simple alias, it doesn't recognize the file:

Error: Cannot find module '@root/my-module.js'

You can replicate this issue with these 3 files:

package.json

{
  "name": "ava-alias",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "ava"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "ava": "^2.4.0",
    "esm": "^3.2.25",
    "module-alias": "^2.2.2"
  },
  "ava": {
    "require": [
      "esm",
      "module-alias"
    ]
  },
  "_moduleAliases": {
    "@root": "."
  }
}

test.js

require('module-alias/register')

import test from 'ava'
//import cube from './my-module.js'  // working
import cube from '@root/my-module.js' // not working

test('cube of 3 is 27', t => {
    t.is(cube(3), 27)
})

my-module.js

export default function cube(x) {
  return x * x * x
}

Create an empty folder, save these files there, and then run npm i && npm run test in that directory. Thank you for your assistance!

Answer №1

I encountered the same issue as well. The solution to this problem is to add module-alias/register in your Ava configuration.

Your package.json should be as follows:

{
  "name": "ava-alias",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "ava"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "ava": "^2.4.0",
    "esm": "^3.2.25",
    "module-alias": "^2.2.2"
  },
  "ava": {
    "require": [
      "esm",
      "module-alias/register"
    ]
  },
  "_moduleAliases": {
    "@root": "."
  }
}

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

The app in NextJs encounters layout issues on all pages due to a break in

I've developed a NextJs application using npx create-next-app and attempted to implement my own custom layout. However, this resulted in breaking the app unexpectedly without any clear reason. The project structure includes: components -> Footer.j ...

My `npm start` script keeps throwing the error: 'run' is not a recognized as a command, internal or external, operable program or batch file. What could be causing this issue?

When I run the command "npm start", instead of getting the local host IP, I encounter this issue. [email protected] start run npm lite 'run' is not recognized as an internal or external command, operable program or batch file.** I also i ...

What are the potential reasons for a "child-removed" event failing to trigger?

Let's look at a simplified version of the code: var queueTask = function (taskObject) { var deferred = $q.defer(); // Creating a new task reference & pushing a new Task object to that location var newTaskRef = firebase.database().ref ...

JavaScript Scrolling Functionality Not Functioning as Expected

I have implemented a scroll function on my website $('#lisr').scroll( function() { if($(this).scrollTop() + $(this).innerHeight()>= $(this)[0].scrollHeight) { //Perform some action here } } However, I am encountering an ...

What is the correct way to promise-ify a request?

The enchanting power of Bluebird promises meets the chaotic nature of request, a function masquerading as an object with methods. In this straightforward scenario, I find myself with a request instance equipped with cookies via a cookie jar (bypassing req ...

Issue with jQuery.off when using a dynamic function name

I am currently implementing a modular pattern for writing my JavaScript code and it has been an enjoyable experience! However, I have encountered a challenging situation. My Namespace structure looks like this: var settings, handlers, objects, Namespace ...

How to retrieve the value of an observable from a regular JavaScript array in Knockout JS?

Context In my project, I am working with a plain JavaScript array that starts off empty but gets populated with Knockout observables later on. These values are numbers and I need to compare them with values in another Knockout observable array. The issue ...

What is the best way to connect input values with ngFor and ngModel?

I am facing an issue with binding input values to a component in Angular. I have used ngFor on multiple inputs, but the input fields are not showing up, so I am unable to push the data to subQuestionsAnswertext. Here is the code snippet from app.component ...

Unable to access the property '__reactAutoBindMap' as it is undefined

I've been struggling with setting up server side rendering with React for the past week. It's a new project using an express server and I'm trying to render a simple hello world react app that utilizes react-router-component. To get some he ...

Encountering issues while trying to run npm install for an Angular 7 application, specifically receiving an error stating: "Module not found: @angular-devkit/build-ng-packagr." This error is hindering

I don't have much experience with JavaScript, node, npm, Angular, etc. My expertise lies in TypeScript as I am still a beginner. However, I recently inherited an application that requires maintenance to resolve a cross-site cookie issue. As I attempt ...

Navigating from the Login Page to the Dashboard in Vue.js following successful token validation

I am facing an issue with the code that is supposed to redirect the User to the dashboard page if they have a token. Despite generating a JWT token from my Spring Boot backend and sending it to Vue for processing, the redirection is not working as expect ...

How do I execute a Next.js script that utilizes `fs` and `sharp` during development with Webpack?

I'm working on creating a basic GIFPlayer that displays a GIF when the play button is clicked, and shows a PNG otherwise: <img className="w-full h-full" src={isPlaying ? gifPath : imgPath} alt={pic.alt} /> Since I only have a GIF file ...

Problem with setting up Rect JS

Just starting out with react js, I've successfully installed the stable version of node js. Verified the node version and npm version, everything seems to be working fine. However, when attempting to install react using "npm init react -app" & "npx cr ...

Making a REST API call with an ID parameter using Angular

I am currently working on an Angular application that interacts with a REST API. The data fetched from the API is determined based on the customer ID, for example: api/incident?customer_id=7. I am unsure of how to incorporate this into the API URL and serv ...

Interacting between frames with jQuery

I have main_page.htm with the following frameset structure: <frameset rows="30,*" frameborder=0 border=0> <frame name="top_frame" src="top.htm"> <frame name="bottom_frame" src="bottom.htm"> </frameset> The content in ...

error: unrecognized command (npm)

I'm currently in the process of setting up a connector for Elm-d3 that I came across on Github. Elm is a functional-reactive programming language created by Evan Czaplicki d3.js is a popular graphics meta-library developed by Michael Bostock El ...

Converting a database query result into a JavaScript variable: A step-by-step guide

I've been struggling with this problem for a day now and I feel like giving up. My main goal is to export the query result as a string (specifically dataString) so that I can easily import it as a string in my external .js file. module.exports.getKl ...

Saving Information to a Specific Location on the Client Side in a CSV File

I am currently working on a static application that uses Angular JS technology. My goal is to write data into a CSV file at a specific path in order for another API to read the data from that location. Despite searching extensively on the internet, I hav ...

Suggestions for this screenplay

I am completely new to the world of coding and computer languages, and I could use some guidance on how to utilize this script for a flash sale. setInterval(function() { var m = Math.floor((new Date).getTime()/1000); if(m == '1476693000000& ...

updating the row of an html table with elements from a javascript object

I am faced with the task of dynamically adding rows to a table based on the number of elements in my JavaScript object. The object consists of keys and arrays of values. userobject={ ID: [1,2,3] IP_Address: ["12.21.12 ...