Code Monkey home page Code Monkey logo

typescript's Introduction

@ava/typescript

Adds TypeScript support to AVA.

This is designed to work for projects that precompile TypeScript. It allows AVA to load the compiled JavaScript, while configuring AVA to treat the TypeScript files as test files.

In other words, say you have a test file at src/test.ts. You've configured TypeScript to output to build/. Using @ava/typescript you can run the test using npx ava src/test.ts.

Enabling TypeScript support

Add this package to your project:

npm install --save-dev @ava/typescript

Then, enable TypeScript support either in package.json or ava.config.*:

package.json:

{
	"ava": {
		"typescript": {
			"rewritePaths": {
				"src/": "build/"
			},
			"compile": false
		}
	}
}

Both keys and values of the rewritePaths object must end with a /. Paths are relative to your project directory.

You can enable compilation via the compile property. If false, AVA will assume you have already compiled your project. If set to 'tsc', AVA will run the TypeScript compiler before running your tests. This can be inefficient when using AVA in watch mode.

Output files are expected to have the .js extension.

AVA searches your entire project for *.js, *.cjs, *.mjs, *.ts, *.cts and *.mts files (or other extensions you've configured). It will ignore such files found in the rewritePaths targets (e.g. build/). If you use more specific paths, for instance build/main/, you may need to change AVA's files configuration to ignore other directories.

ES Modules

If your package.json has configured "type": "module", or you've configured AVA to treat the js extension as module, then @ava/typescript will import the output file as an ES module. Note that this is based on the output file, not the ts extension.

Add additional extensions

You can configure AVA to recognize additional file extensions. To add (partial†) JSX support:

package.json:

{
	"ava": {
		"typescript": {
			"extensions": [
				"ts",
				"tsx"
			],
			"rewritePaths": {
				"src/": "build/"
			}
		}
	}
}

If you use the allowJs TypeScript option you'll have to specify the js, cjs and mjs extensions for them to be rewritten.

See also AVA's extensions option.

† Note that the preserve mode for JSX is not (yet) supported.

typescript's People

Contributors

adam-lynch avatar conaclos avatar novemberborn avatar szmarczak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

typescript's Issues

Excessive memory use in ava 4, leading to out of memory errors

What you're trying to do
I have a suite of tests that run and work fine with Ava 3. I would like to upgrade to Ava 4.

What happened
When I upgraded to Ava 4, I started to get constant timeouts, especially when I ran with -u. I tracked the issue down to Javascript heap memory being exhausted. On a recent run, I opened my Activity Monitor (I'm on Mac Moneterey), and saw over 10GB is memory being used by node shortly before the test run exited with another timeout.

I tried running with every version from ava 4.0.0 through the current version 4.3.1, and none of them finished with all my tests running.

I didn't not change anything about the config when I upgraded (other than renaming the file to mjs); though I also tried disabling the worker threads, that didn't help the issue.

I saw the timeout failures on my local machine, as well as our Jenkins/Docker-based CICD build machine.

What you expected to happen
I expect that tests working under Ava 3 would still work with Ava 4. I would expect that memory consumption would be similar (though I still find it excessive, especially for running in a CI/CD build machine).

I have been unable to find relevant documentation to help me understand what's going on, though it probably has something to do with ts-node and compilation. It would be helpful if there were actual error messages other than just a timeout message.

I found github discussions suggesting precompiling, or using transpile-only, but those solutions didn't work for me; I got a bunch of type-related errors as ava couldn't seem to resolve various identifiers. I'm also not sure if it's possible to maybe use ava with my webpack bundle instead of the source tree.

Any pointers to documentation describing alternatives to just running ts-node would be helpful

Config files:

ava.config.mjs:

export default {
  extensions: ['ts', 'tsx'],
  files: ['src/**/*.test.*'],
  verbose: true,
  failWithoutAssertions: true,
  environmentVariables: {
    TS_NODE_PROJECT: './src/tsconfig.json',
    TS_NODE_COMPILER_OPTIONS: '{"module":"commonjs"}',
  },
  require: [
    './_setup-unit-test-env.js',
    'tsconfig-paths/register',
    'ts-node/register',
    'isomorphic-fetch',
  ],
  timeout: '80s',
}

tsconfig.js:

{
  "compilerOptions": {
    "experimentalDecorators": true, // @computed
    "baseUrl": ".",
    "typeRoots": [
      "../node_modules/@types",
    ],
    "sourceMap": true,
    "module": "es6",
    "moduleResolution": "node",
    "target": "es6",
    "outDir": "build",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "paths": {
      "~/*": ["./*"]
    },
    "jsx": "react-jsx",
    "jsxImportSource": "preact"
  },
  "include": ["./"],
  "ts-node": {
    "files": true
  },
  "files": ["./environment.d.ts"]
}

invoke via package.json script:
"test": "c8 ava",

Node version 16.16.0, but also tested with 18.7.0

Allow testing entire production bundles while using specific .ts files for type support.

What you're trying to do:

We want to run tests against production assets which happens to be bundled while using the ts files for types in the tests themselves.
The reasoning is that we want to run tests against final assets that will be deployed.

As I understand this, the expectation is that there is a .ts file for the generated .js.
But how does it work if a bunch of .ts files are compiled and bundled into a single .js file?

Why you can't use AVA's Babel support for this

N/A - If it's possible I'd love to know how.

And maybe how you think AVA could handle this

N/A

Edit: Nevermind, doesn't seem to be a popular notion.

Error: tsx must be loaded with --import instead of --loader

I'm trying to simply get Ava up and running in my project. I'm using the latest version of NodeJS available to me, v21.2.0. I tried configuring it according to the official documentation, with the special note about NodeJS v20:

package.json

{
  // ...
  "scripts": {
    "test": "NODE_OPTIONS='--loader=tsx' ava"
  },
  "ava": {
    "extensions": { "ts": "module" }
  }
}

This is the output of npm test:

> NODE_OPTIONS='--loader=tsx --no-warnings' ava


node:internal/process/esm_loader:34
      internalBinding('errors').triggerUncaughtException(
                                ^
Error: tsx must be loaded with --import instead of --loader
The --loader flag was deprecated in Node v20.6.0
    at Q (file:///[...]/node_modules/tsx/dist/esm/index.mjs:1:1880)
    at Hooks.addCustomLoader (node:internal/modules/esm/hooks:180:24)
    at Hooks.register (node:internal/modules/esm/hooks:154:16)
    at async initializeHooks (node:internal/modules/esm/utils:243:5)
    at async customizedModuleWorker (node:internal/modules/esm/worker:109:13)

Node.js v21.2.0

I'm running Ava version 5.3.1. Trying the same thing with --import=tsx yields another error:

> NODE_OPTIONS='--import=tsx --no-warnings' ava


  Uncaught exception in src/test.ts

  TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /[...]/src/test.ts

  ✘ src/test.ts exited with a non-zero exit code: 1
  ─

  1 uncaught exception

feat: monorepo support

Please provide details about:

  • What you're trying to do
    Use ava/typescript in a monorepo

  • Why you can't use AVA's TypeScript support for this
    Need the compilation process when running/debugging tests to be identical to the build of the source code in general (no babel).

  • And maybe how you think AVA could handle this
    Add flexibility in the ava typescript rewrite path configurations to support relative paths (relative to the test case .ts files) so that each package's own build directory in the monorepo can be referenced without having to reference all of them one by one.

Directory structure:

packages/
├─ pkg-a/
│  ├─ dist/
│  │  ├─ lib/
│  │  │  ├─ index.js
│  ├─ src/
│  │  ├─ index.ts
├─ pkg-b/
│  ├─ src/
│  │  ├─ index.ts
│  ├─ dist/
│  │  ├─ lib/
│  │  │  ├─ index.js

Rewrite rule to capture all packages:

{
  "./packages/pkg-*/src/": "./packages/pkg-*/dist/lib/"
}

Import problems within test files

First up, it's more a cry for help than a bug report, I think maybe it's a bug though.

What you're trying to do:

I just found an inactive NPM module that I wanted to use and tested it out, it worked but had some stuff that's missing for me. So I tried cloning it and getting it to run locally, so I can add the features I want. I bumped the dependence versions, got it to compile again, moved to ESLint from TSLint and tried running the tests. The tests didn't work, all local dependencies were not recognized, so I began to experiment. The tests are written in JS, the lib itself is written in ts. The test imported the ts files directly from source, so for example: '../src/docker' that gave me a:

 Uncaught exception in test/docker.js

  Error [ERR_MODULE_NOT_FOUND]: Cannot find module '~/node-docker-api/src/docker' imported from ~/node-docker-api/test/docker.js

so I changed it to '../src/docker.ts'':

  Uncaught exception in test/docker.js

  TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for ~/node-docker-api/src/docker.ts

then I thought maybe I need to import from the compiled lib folder, so I moved on to '../lib/docker'':

  Uncaught exception in test/docker.js

  Error [ERR_MODULE_NOT_FOUND]: Cannot find module '~/node-docker-api/lib/docker' imported from ~/node-docker-api/test/docker.js

than to '../lib/docker.js':

  Uncaught exception in test/docker.js

  Error [ERR_MODULE_NOT_FOUND]: Cannot find module '~/node-docker-api/lib/container' imported from ~/node-docker-api/lib/docker.js

and finally '../lib/docker.ts'

  Uncaught exception in test/docker.js

  Error [ERR_MODULE_NOT_FOUND]: Cannot find module '~/node-docker-api/lib/docker.ts' imported from ~/node-docker-api/test/docker.js

So it didn't work
then I tried fixing the problem with AVA typescript with the configuration:

"ava": {
    "files": ["test/**/*.js"],
    "typescript": {
      "extensions": [
        "ts",
        "tsx"
      ],
      "rewritePaths": {
        "src/": "lib/"
      },
      "compile": "tsc"
    }
  },

Didn't work I changed the ts config module option from commonjs to ESNext didn't work either.

A now I don't know anything I can try to get it working.
I just need it to import the classes from the lib, that's all.

Sample code:

It's not quite a minimal example, but it's quite small: https://github.com/dustsucker/node-docker-api any changes I made are reflected int that fork of the NPM module.

As for AVA version, I use 5.3.1.

I hope you can help me :)

best regards
Titus Breede

Throw when loading a TypeScript file that is not covered by the rewrite paths

This is more like an anti-bug than an actual bug. But it seems like this project works even when I provide a nonsensical rewritePaths entry, for example:

"typescript": {
  "rewritePaths": {
    "meaninglessdirectory/": "jababababa/"
  }
},

Shouldn't ava crash if this occurs?

Here's the repository ("ava" branch): https://github.com/vedantroy/typecheck.macro

Check out the repository, switch to the ava branch, and then run npm i && npm run test.

What happens The tests run successfully. You can show that ava is not using the js file by renaming temp_build/test.js to temp_build/foobar.js and then executing npm run test:run. The tests will still execute. You can even modify tests/test.ts, maybe add an extra console.log statement, then run npm run test:run, and the new output will be printed. Does ava now support typescript natively, or am I missing something?

What you expected to happen: Ava should crash or something because inside of my package.json, I have a meaningless typescript configuration.

Ava version: 3.7.1

Document how to use source map support

This provider doesn't translate error stack traces using source maps. We should document how you can set that up yourself, by installing source-map-support and adding source-map-support/register to AVA's require configuration.

rewritePaths is less restrictive than expected

Thank you for this project! I migrated bitcoin-ts recently, and I just wanted to note an issue I had.

My Typescript project builds the same source to two different output locations, one build/main/ for Node.js usage and one build/module/ for consumers which use build tools like Rollup.

I primarily test against the build/main/ build, so the configuration seemed simple:

  "ava": {
    "typescript": {
      "rewritePaths": {
        "src/": "build/main/"
      }
    }
  }

But with that configuration, AVA was also trying to test files in the build/module/ folder. I ended up needing to add an exclusion:

  "ava": {
    "typescript": {
      "rewritePaths": {
        "src/": "build/main/"
      }
    },
    "files": [
      "!build/module/**"
    ]
  }

This works well now, so I'm happy to leave it as-is. I just wanted to mention that it differed from my initial impression of how rewritePaths would work. I thought setting src/ to build/main/ would map files in those directories one-to-one, but AVA seems to also be searching in build/module/ without the specific exclusion.

(Thanks again for v3 of AVA and the improved Typescript integration! Even debugging is working beautifully now.)

A bit more guidance on how to set things up properly

I'm kinda confused how I'm supposed to properly use this package alongside baseUrl, I think I'm holding it wrong lol.

So I upgraded AVA to ava@next (4.0.0-rc.1) and installed the latest @ava/typescript (3.0.1). My project uses TypeScript Project References, and dumps files into a .build-tsc/ directory, so I set compile: false, and edited my test script to compile before running ava.

Project has a src/ directory at the root containing code, and a tests/ directory containing a mix of tests (file extension *.test.tsx?) and utilities for tests (just ending in .ts). I set baseUrl in my tsconfig to the package root, and before trying @ava/typescript, I was just setting NODE_PATH to .build-tsc so that Node could find all the proper files.

That's fine, but the main downsides are A) all the errors are in the compiled JS instead of the TS, making it harder to understand where the errors come from; and B) pretty sure it just doesn't work with JSX at the moment (but that's less pressing since I'm mostly testing backend business logic).

So trying out @ava/typescript, I set my config as follows:

// package.json
  "scripts": {
    "test": "tsc --build tests && ava",
    // ...
  },
  "ava": {
    "typescript": {
      "rewritePaths": {
        "src/": ".build-tsc/src/",
        "tests/": ".build-tsc/tests/"
      },
      "compile": false,
      "extensions": ["ts", "tsx"]
    },
    "files": [
      "./tests/**/*.test.ts?(x)"
    ]
  }

This evidently is not correct, as I get errors like the following whenever a test tries to import anything in src:

  Uncaught exception in tests/utility/markup-description.test.ts

  Error: Cannot find module 'src/utility/array'
  Require stack:
  - /Users/omar/code/spinach/web-app/.build-tsc/tests/utility/markup-description.test.js
  - /Users/omar/code/spinach/web-app/node_modules/ava/lib/worker/base.js

And then if I set NODE_PATH again to .build-tsc, then it works, but once again it's no different in that error line numbers are in the original JS files, not the TS ones.

So yeah I'm not totally sure how to A) make TypeScript baseUrl (and relatedly paths which I'm not using right now) work, and B) how I should be doing things to get the line numbers to be those of the TypeScript files. I think some more detailed examples/documentation for these kinds of use cases, or at least a disclaimer that this isn't supported, would be helpful for me!

AVA select `.d.ts` files as test files

AVA will select all .ts files as test files. It should automatically ignore .d.ts files. We'll have to make changes in AVA so this package can communicate exclusion patterns, not just file extensions.

For now, the workaround is to add !**/*.d.ts to the files patterns configuration.

Can't get TS esm working on async esm babel config and esm ava.config.mjs

I'm using node 18 LTS and trying to get ESM working.

@novemberborn as per #5.
I don't think @ava/typescript identifies *.mts test files as ES modules properly, after compiling with babel-preset-typescript instead of tsc and "type": "module".

I'm importing shared esm babel and ava configs from separate packages - i.e. monorepo with separate config-testing workspace for ava and config-babel, for babel instrumentation respectively (yarn berry workspaces tbe).
Using experimental @babel/register/experimental-worker.js to be able to load .babel.mjs config.

Everything is "type": "module" in here.

.ava.config.mjs

import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export default {
  files: [
    'test/**/*.mts',
  ],
  typescript: {
    extensions: [ 'ts', 'mts', 'cts', 'tsx', 'js','jsx', 'cjs', 'mjs' ],
    rewritePaths: {
      'src/': 'dist/',
    },
    compile: false,
  },
  require: [
    `${__dirname}/Register.js`,
  ],
  failFast: true,
  failWithoutAssertions: false,
  verbose: true,
};

.babelrc.mjs

export default {
  sourceType: 'module',
  targets: {
    node: 'current',
    esmodules: true
  },
  env: {
    coverage: {
      plugins: ['istanbul']
    }
  },
  presets: [
    '@babel/preset-typescript',
    [
      '@babel/preset-env',
      {
        loose: true,
        useBuiltIns: false,
        modules: false,
        bugfixes: true,
        targets: {
            node: 'current'
        },
      }
    ]
  ]
};

I'm not sure if worker is able to identify that it's a module over here. I'm passing the js extension but I don't think I'm able to force using ES modules, by default, and fallback to CommonJS if the import had failed.

Maybe it's worth adding 'ts' 'mts' extensions explicitly over here ?

For some reason it doesn't pick .mts text files as ES Modules.

I'd like to keep babel instrumentation due to certain TSC compatibility issues with the existing coverage report tools, including Node internal coverage reporter.

[Q] Proper setup / `Cannot use import statement outside a module`

Please provide details about:

  • What you're trying to do
  • What happened
  • What you expected to happen

Please share relevant sample code. Or better yet, provide a link to a minimal reproducible example.

We'll also need your AVA configuration (in package.json or ava.config.* configuration files) and how you're invoking AVA. Share the installed AVA version (get it by running npx ava --version) and @ava/babel version (from your package.json file).

I try to setup AVA 4 with TS for a bigger project. But to simplify things I reduce the problem to a simply project: https://github.com/sculpt0r/AVAwithTS

Now I try to run npm run test. The results is:
image

I tried to follow the documentation of AVA & this plugin:

  • installed AVA (4.3.0)
  • installed @ava/typescript (3.0.1)
  • also I found that it should be useful to additionally install source-map-support - so I did it and in cfg file I added:
"require": ['source-map-support/register']
  • in .tsconfig the outDir is set to the same directory (build) as in AVA config rewrite paths
  • also the compile is set to tsc, but if I try to run tests with compile set on false and the build directory already contains js files - I receive the same results as in the screenshot above

I assume I'm missing something - but I'm not sure what? Is it possible to take a look at the sample project: https://github.com/sculpt0r/AVAwithTS, then run npm i and then npm run test.

Perform compilation

It should be possible to compile the TypeScript project before tests are run.

We should be able to control TypeScript programmatically. There is a feature to cache some of the compilation work, for faster subsequent compilation runs. We should use this.

As alluded to in #2 we should probably only support configuration files in the project directory itself (next to package.json files).

I'm not sure where to write the output files. Perhaps just follow the TypeScript configuration. With #2 done that makes it easiest to subsequently load the test files.

I'm not sure how to handle compilation errors. We could just write the files and run the tests. We could also explore an integration with AVA to surface errors better.

This should work automatically with AVA's watch mode, since AVA invokes compilation before every test run.

Investigate watcher interactions

AVA's watcher may be watching both source files and the TypeScript build output. It must watch the source files, otherwise it won't know to rerun tests. But there's no point in rerunning tests until the build output has changed.

Delaying the watcher may work but this is not configurable. Perhaps if the watcher could figure out it should wait for a rewritten path to be updated too that may work. It'll require changes to how AVA and this package interact.

Document how to use this with mixed projects

If your TypeScript project still contains JavaScript code then not to worry, this package should still work. However you'll have to explicitly specify the js and ts extensions. It'd be good to add this to the documentation.

Investigate custom, TypeScript-specific assertions

Coming out of discussions in avajs/ava#2449 we may want to consider supporting additional assertions for use with TypeScript. Say a t.guard(obj, fn) which can be used in an if condition:

if (t.guard(fooOrBar, isFoo)) {
  // Do stuff know that we know fooOrBar is Foo
}

Of course AVA does not support custom assertions yet, but keep an eye on avajs/ava#2435.

We'll also have to consider how you might import a test function that has these assertions installed.

Support typed configuration via an `ava.config.ts` file

It'd be useful if we could use TypeScript to define our Ava configurations via an ava.config.ts file.

Ideally, we'd be able to structure them like so:

// Importable `Configuration` type
import { Configuration } from 'ava';

// Typed configuration object
const configuration: Configuration = {
  // ... config goes here
};

export default configuration;

Webpack supports similar functionality with webpack.config.ts files (although I believe ts-node is required for those).

ts-node improvements for ava projects?

I came across avajs/ava#1109 which lists several criticisms of ts-node and predates some recent improvements.
For example, ts-node has since implemented an ESM loader which I believe can handle #5.
#20 -- source-map-support -- is enabled out-of-the-box in ts-node.
We allow all configuration to be placed in your tsconfig.json.
And we have an swc integration that will be in the next release, allowing users to opt-in to much faster compilation than we can get with babel or typescript.

All that to say, if you have time, I would love to talk about any other bugs , limitations, or inconveniences that your users hit with ts-node. At the very least it will give me some useful data points for improving ts-node. A big goal of mine is to make TS and node tooling feel cleaner, easier, and require less boilerplate.

If you have any thoughts, please let me know.

Add `"types"` entries to the `"exports"` property of package.json, to allow consumption from Typescript with the new `Node16` module resolution strategy

Is your feature request related to a problem? Please describe.

I'm unable to consume "ava" from Typescript 4.7, when module resolution is set to Node16

Describe the solution you'd like

Add "types" entries to the "exports" property of package.json

Describe alternatives you've considered

None

Additional context

The following should suffice

"exports": {
  ".": {
    "types": "./index.d.ts"
    "import": "./entrypoints/main.mjs",
    "require": "./entrypoints/main.cjs"
  },
  "./eslint-plugin-helper": "./entrypoints/eslint-plugin-helper.cjs",
  "./plugin": {
    "import": "./entrypoints/plugin.mjs",
    "require": "./entrypoints/plugin.cjs"
  }
},

Ava watch does not work with pre-compile option

Please provide details about:

  • What you're trying to do

Ava watch mode with this package.

{
  "ava": {
    "files": [
      "src/**/*.test.ts"
    ],
    "typescript": {
      "rewritePaths": {
        "src/": "build/"
      },
      "compile": "tsc"
    }
  }
}
  • What happened

ava --watch

If I change a source file or test file the runner is not restarted. If I do the same with ts-node/register it works.

  • What you expected to happen

Ava runner should rerun on file change.

ava: 3.15.0

Source maps ignored and incorrect line shown when using nyc

Hi there,

First off, thank you for your work on this 😄. I have everything seemingly working butI keep seeing errors pointing to the first line of the built file. For example, notice how the error points to the use strict of line 1.

Screen Shot 2020-04-16 at 9 09 06 PM

I look at all the tickets and the closest was #19. I feel like I have something misconfigured but still stuck and hope someone can help. Thanks!

// test/utils/order.ts
import test from 'ava';

import {formatOrderDate} from '../../src/utils/order';
test('formatOrderDate > pretty prints the date', (t) => {
  t.is(formatOrderDate(1586130298135), 'April 5, 2220');
});
// build-temp/tests/utils/order.js
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ava_1 = __importDefault(require("ava"));
const order_1 = require("../../src/utils/order");
ava_1.default('formatOrderDate > pretty prints the date', (t) => {
    t.is(order_1.formatOrderDate(1586130298135), 'April 5, 2220');
});
//# sourceMappingURL=order.js.map
// ava.config.js
export default {
  concurrency: 5,
  failFast: true,
  files: ['tests/**/*', '!tests/test-helpers'],
  failWithoutAssertions: false,
  nodeArguments: ['--trace-deprecation', '--napi-modules'],
  typescript: {
    extensions: ['ts', 'tsx'],
    rewritePaths: {
      '/': 'build-temp/',
    },
  },
  verbose: true,
};
// package.json
{
  "devDependencies": {
    "@ava/typescript": "^1.1.1",
    "ava": "^3.7.0",
  },
  ...
  "scripts": {
    ...
    "test": "test:build && nyc --reporter=text --reporter=text-summary ava",
    "test:build": "tsc --build tsconfig.tests.json"
  }
}
npx ava --version: 3.7.0
// tsconfig.tests.json
{
  "compilerOptions": {
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "build-temp"
    "resolveJsonModule": true,
    "sourceMap": true,
    "target": "esnext"
  },
  "include": ["src/**/*.ts", "src/**/*.json"],
  "exclude": ["dist", "node_modules", "**/*.spec.ts"],
  "baseUrl": ".",
  "paths": {
    "*": ["node_modules/*", "src/types/*"]
  }
  "include": ["tests/**/*.ts", "src/**/*.ts", "src/**/*.json"]
}

[Docs] What is the practical difference of using @ava/typescript? Should I expect automagic source mapping?

Note: I have phrased this issue mostly as a question, but please look at it as a request for documentation improvement - I looked around but didn't find anything on this.


My @papb/zip module is written in TypeScript and I currently test it with ava, but without @ava/typescript.

Today I tried to configure @ava/typescript on it. However, although it works, I could not see any practical difference. I thought perhaps source mapping would work automagically, but I still get outputs based on the compiled file.

For example, adding a simple failing test as follows:

// test/test.ts
import test from 'ava';

test('Tests not ready...', t => {
	t.fail();
});

Still yields:

image

Note the presence of ava_1.default.

This was the only thing I was expecting to change. If this still works as before, what is the practical advantage of starting to use @ava/typescript?

Surprising rewritePaths needed

My source files are organized like this:

./src/
    example.ts
    second-example.ts
    tests/
      test-example.ts
      test-second-example.ts

My tsconfig.json looks like this:

{
  "compilerOptions": {
    "outDir": "./build",
    "allowJs": true,
    "target": "es5"
  },
  "include": ["./src/**/*"]
}

Which results in output like this

./build/
    src/
      example.js
      second-example.js
      tests/
        test-example.js
        test-second-example.js

I installed @ava/typescript and added rewritePaths to package.json as instructed in this library's readme, like this:

"ava": {
  "typescript": {
    "rewritePaths": {
      "src/": "build/"
    }
  }
}

But then running ava or npx ava src/tests/test-example.ts or other variations kept resulting in fatal errors like:

Uncaught exception in src/tests/test-example.ts

Error: Cannot find module '/Users/dsernst/Documents/myproject/build/tests/test-example.js'

It took me a while to figure out what was going on.

Note that it's missing the /src/ directory between /build/ and /tests/.

So after much tweaking, I was finally able to get it working with:

  "rewritePaths": {
    "src/": "build/src/"
  }

Maybe this is obvious, and I was just being stupid, but I'm putting this up here in part to help anyone else that comes across a similar issue.

version info:

@ava/typescript: 1.1.1
ava: 3.9.0
typescript: 3.9.5

node v12.16.3

Automagically determine rewrite paths

It should be possible to resolve the TypeScript configuration (including extended configurations) to determine what source directories are output where. That way, users won't have to configure the rewrite paths.

I'm not sure if TypeScript supports multiple configuration files within a project. Babel does, but AVA's Babel support ignores such configuration files. It'll be simplest to do the same here.

This means we'll assume the nearest TypeScript configuration file is in the project directory itself.

Support ESM test files

Once avajs/ava#2345 has shipped it should be possible to configure AVA to load ts files as ES modules.

This means we need to import them, instead of using require.

We should also explore if there may be a way to configure this within the typescript configuration.

Issue with usage of ESM repository

I am trying to switch my repository from CommonJS to ESM, as part of this migration I encounter some issue with the AVA configuration since when I launch the test I get the following issue:

  Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: \ava-repro\src\multiply.test.ts
  require() of ES modules is not supported.
  require() of ava-repro\src\multiply.test.ts from \ava-repro\node_modules\ava\lib\worker\base.js is an ES module file as it is a .ts file whose nearest parent package.json contains "type": "module" which defines all .ts files in that package scope as ES modules.
  Instead change the requiring code to use import(), or remove "type": "module" from \ava-repro\package.json.

In order to help you found the issue in the configuration, I have reproduced the migration issue within this reproduction repository: https://github.com/Amachua/ava-repro (and you can see the issue directly in the pipeline build here).

Did I miss something in the configuration to make it properly work with ESM?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.