简体   繁体   English

如何在 AVA 测试中设置别名

[英]How to set an Alias in AVA tests

I'm trying to set alias globally in my project without using Webpack, Babel, etc. Right now I have a simple test with AVA .我正在尝试在我的项目中全局设置别名,而不使用 Webpack、Babel 等。现在我对AVA进行了简单的测试。

I'm using module-alias npm package that let me set in package.json my aliases.我正在使用模块别名npm package 让我设置 package.Z466DEEC5 我的别名76ECDF5FCA6D38 我的别名76ECDF5FCA6D38 However, when I try to just create a simple example following the documentation with a basic alias it doesn't find the file:但是,当我尝试在具有基本别名的文档之后创建一个简单的示例时,它找不到该文件:

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

You can reproduce this example with these 3 files:您可以使用以下 3 个文件重现此示例:

package.json 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测试.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我的模块.js

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

Save these files to an empty folder and then in that path in your terminal: npm i && npm run test将这些文件保存到一个空文件夹,然后在终端的该路径中: npm i && npm run test

Maybe I'm missing same basics, thank you so much for time and help!也许我缺少相同的基础知识,非常感谢您的时间和帮助!

I ran into this same issue.我遇到了同样的问题。 You can solve this by using module-alias/register inside your Ava config.您可以通过在 Ava 配置中使用module-alias/register来解决此问题。

Your package.json should look like:您的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/register"
    ]
  },
  "_moduleAliases": {
    "@root": "."
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM