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

Drop-down Navigation in HTML and CSS is a popular way to create

My navigation menu is functioning well and has an appealing design. The HTML structure for the menu is as follows: <div id="menubar"> <div id="welcome"> <h1><a href="#">Cedars Hair <span>Academy</span></ ...

Ways to verify if Arabic text has been submitted by the user through a form?

Is there a foolproof method for detecting Arabic input in a form before submission? Can Javascript effectively manage this task, or is it better handled by server-side scripts like .NET? I propose implementing a script to immediately block users from ente ...

Encountered an issue when trying to install truffle with the command "npm i truffle -g"

Encountered an unidentified error while trying to install Truffle on my computer... https://i.stack.imgur.com/6GuxV.png Initially, there was an unexpected issue with Python. However, after installing Python, a new error arose npm ERR! code 1 npm ...

Arrange JSON information in an HTML table with distinct header rows for every data category

I have a JSON object with a key:value pair named callRoot. Some examples of values for this pair are @S, @C, and @W. There are multiple objects that share the same value and I want to create an HTML table head row at the beginning of each group and repeat ...

Building an Angular module that allows for customizable properties: A step-by-step guide

I am in the process of developing an AngularJS module that will simplify interactions with my product's REST API. Since my product is installed on-premise, each user will need to provide their own URL to access the API. Therefore, it is essential that ...

Populate a shopping cart with items using AngularJS

Greetings from an Angular newbie! I'm currently working on developing a shopping cart specifically designed for college students. The objective is to input the name and price of items into a text field and upon clicking a button, have the item added t ...

Having issues with the functionality of the Material UI checkbox component

Having issues with getting the basic checked/unchecked function to work in my react component using material UI checkbox components. Despite checking everything, it's still not functioning as expected. Can someone please assist? Here's the code s ...

Best practices for making an AJAX call to fetch information from a database

I have a database containing a single table. The table includes columns for Company and Time, among others, with Company and Time being crucial. Users can make appointments by filling out a form. Within the form, there are 2 <select> elements - one ...

Using JavaScript with React to invoke an asynchronous action within a component

Within my class, I have implemented some asynchronous actions in the ComponentDidMount method. The code snippet looks like this: componentDidMount(){ // var my_call = new APICall() Promise.resolve(new APICall()).then(console.log(FB)) } class API ...

Difficulty encountered when applying a CSS class with JavaScript

The Javascript function I am currently using is able to select multiple links. This behavior occurs because of the Regular expression I applied with the '^' symbol. I decided to use this approach because my links are in the following format: htt ...

Internal styles are effective, while external styles seem to be less efficient

For some reason, internal CSS is working fine, but external CSS just won't cooperate. I even tried using the code !important, but it's like it doesn't understand. I'm trying to incorporate a gallery into my website, but I've hit a ...

Tips for concealing JavaScript animations beyond specific boundaries?

So I'm delving into the world of javascript/jquery and an amazing idea popped into my head for a webpage effect. Let me break down the design a bit. My website is neatly contained within a wrapper div, ensuring that the content stays at 1000px and ce ...

Transforming an Image URL into base64 format using Angular

I'm currently facing difficulty when attempting to convert a specified image URL into base64. In my scenario, I have a string that represents the image's path. var imgUrl = `./assets/logoEmpresas/${empresa.logoUrl}` Is there a way to directly co ...

Oops! An issue occurred during bundling: Unable to locate preset "module:metro-react-native-babel-preset" in the directory "C:\Users\..."

I recently started working with react-native and I keep encountering an error when I execute react-native run-android My package.json was functioning properly before, but now it appears to be causing issues. This is my current package.json file: { "n ...

What is the best way to ensure a consistent time interval between invoking two functions in JavaScript?

Is there a way to create a code that will call one function, let's say toStart(), and then immediately call another function, toStop(), exactly two seconds after the first function is initiated? I want this process to continue until a specific button, ...

Looking to expand the width of the sub menu to reach the full width of the

Is there a way to use CSS to make a sub-menu start from the left side of the screen instead of starting it below the parent item? nav { margin: 0 auto; text-align: center; } nav ul ul { display: none; } nav ul li:hover > ul { di ...

JavaScript: How to Build a Digital Grocery List with Browser Storage

Struggling with a tough exercise question, I could use some help deciphering it. https://i.stack.imgur.com/V5he2.png Here is how I've started the code: <!DOCTYPE html> <html> <head> <title></title> <script> fun ...

What is required to run npm rebuild node-sass --force following each instance of a `yarn add` command?

As I attempt to set up the isemail npm library, everything appears to be going smoothly. However, when I execute yarn start:dev, which essentially runs "npm run build:dev && ./scripts/gendevconfig.sh && cross-env BABEL_DISABLE_CACHE=1 NODE_ ...

Storing property data outside of the render method in ReactJS is key for efficient

I have encountered an issue while attempting to map data outside of the render method in my function and return it within the render. The mapping error is causing confusion as I am uncertain about its underlying cause. Below is the function responsible fo ...

I'm looking for some help with creating a visualization using JavaScript or Python. Can anyone offer some guidance?

// Defining the dimensions and margins of the graph var width = 460 var height = 460 // Appending the svg object to the body of the page var svg = d3.select("#my_dataviz") .append("svg") .attr("width", width) .attr("height", height) // Reading ...