-
Notifications
You must be signed in to change notification settings - Fork 455
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Tests fail when using TypeScript project references #1648
Comments
This one might be related to your case microsoft/TypeScript#37239 In general, ts-jest uses typescript api to read tsconfig and resolves the config to fetch to typescript compiler. In your case, it cannot find enough configs to make tests pass. Your case is similar to #766 |
Thanks, that did the trick! |
@FantasticFiasco what did the trick? I couldn't see any actionables in the two links that @ahnpnl posted. I'm trying to leverage the new "Solution Style" config as introduced in microsoft/TypeScript#37239, so I have a
But when I run my tests they all fail because |
@ryami333 As I recall the problem was with |
@FantasticFiasco that repo uses a workaround in
But that is a workaround which indicates an underlying bug, and not one that can be applied to my setup either. It's frustrating to see this and other similar issues (such as #766) be closed when they're still reproducible, simply because some people have found a workaround which works for them. |
Note that if you are using TypeScript 3.9 solution style, you might run into issue. By default when no tsconfig specified for It is recommended to specify which tsconfig to be picked up via option |
No that's my point exactly: the root Now, for example, I can have different configs for my Otherwise I have to run |
I was thinking about a new feature that is similar to angular/angular#38003 which will show a warning message when encountering solution style, then automatically fallback to either Running jest is a bit different from tsc so some behaviors of tsc are difficult to implement when combining with jest. |
I'll try not to frustrate you next time 😉 You have a collaborator in the thread, I'm sure that given the correct argumentation the issue can be re-opened. Don't you think? |
I think ts 3.9 has an API for solution style and project references. We can reopen and work on this |
EDIT: I posted this right before seeing your message about the new API in 3.9 🥳 Sorry @FantasticFiasco, on reflection I can see that came across as abrasive. |
Appreciate some ideas to tackle this. I took a quick look at the PR microsoft/TypeScript#37239 and saw some discussions about a function but not quite sure. |
I can help with a repro if nothing else, I'll look into that now. |
There we go :) |
Correct me if I’m wrong. The expectation is test files should be run according to the project config of the project they belong to. For example:
When running tests from root (which runs all tests for all projects), all tests in project A should be run with Quite struggling to find the right approach here . Hi @orta can you help us a bit about this ? |
If my understanding is correct, then yes. It seems that the tsc I happen to know that the Sublime Text Editor's Typescript plugin already seems to be able to apply the correct config for any given file in a Solutions config context. I don't yet know whether this is a feature which they actively developed into the plugin, or whether they just defer to the typescript server's internal |
I am trying to figure out the best approach for this as well. I have two main strategies
Both strategies are valid I think but expect quite different behaviors from ts-jest. I think the mapper is an ok solution for option 1 because the intention is that jest references the source files across multiple TypeScript projects. I think the experience here could be greatly improved if ts-jest resolves a solution tsconfig then assume approach 1 and just use a default tsconfig with sensible defaults for a new project created by TS 3.9 (if you are using a solution tsconfig it's a reasonably up to date project), this tsconfig should automatically have module mappings to be able to resolve the source files for each TypeScript project referenced by the solution tsconfig Number 2 is where it gets hard. Lets say there are 2 jest projects referenced by the root jest config and a shared library, when jest goes to run the tests it needs to ensure the shared library is compiled by typescript (does the TypeScript program handle this sort of concurrency?), once it is compiled then each jest project should be able to resolve the shared module using the I think solutions to both can be shipped in ts-jest, but these two approaches should be separated from a solution point of view. |
@JakeGinnivan thanks a lot for the brainstorming help. I'd like to separate the 2 terms here: Overall, these 2 work almost similar. However, the way
In this scenario, I did a small test for this scenario. The project I have contains
This means when using jest config If Currently, jest transformer doesn't support async, neither TypeScript |
I am going through exactly what @ahnpnl described below. I am posting my use case here in case it is helpful.
I have one monorepo with a package called When I try to run the tests from |
Same issue here.. This workaround https://github.com/FantasticFiasco/axis-maintenance-js doesn't work if you have namespace/interface augmentation.. Test passes but failed when collecting coverage report |
Not sure if this is the same use case as you all, but in my ts monorepo example in these test scripts you can see how I have to do for example:
instead of just This is because this project (webapi) depends on lib via ts project references, but whatever ts-jest is doing under the hood it does not seem to be behaving like the |
@rhyek same. if i run if i do not build myself, then it complains So, bottom line is that it seems that ts-jest is not doing what tsc -b would do, so when in watch mode, i really suffer. |
I have the exact same issue as @tommysullivan described. ts-jest should build like |
I want to make clear something: We can still support project references but maybe only partially and definitely won't be exact the same like
I hope this makes clear to everyone the difference between |
Hi @ahnpnl thanks for the clarification. The DX isn't great in that common scenario. |
Hi, So after spending several hours on this - I was able to make this work in my monorepo. This is my jest.config.ts, hopefully it helps others here: import { defaults as tsjPreset } from 'ts-jest/presets'
import type { Config } from '@jest/types'
import type { InitialOptionsTsJest } from 'ts-jest/dist/types'
// there are some typing issues in the jest/types library we fix here
type JestConfig = Omit<InitialOptionsTsJest, 'projects'> & {
projects?: Partial<
| (Omit<Omit<Config.ProjectConfig, 'transfrom'>, 'moduleNameMapper'> & {
transform: any
moduleNameMapper: Record<any, any>
})
| Config.Glob
>[]
}
const config: JestConfig = {
preset: 'ts-jest',
collectCoverageFrom: ['packages/**/src/**/*.(ts|tsx)'],
coverageReporters: ['lcov', 'text'],
cacheDirectory: '.jest/cache',
projects: [
{
testMatch: ['<rootDir>/packages/frontend/tests/**/*.(spec|test).*'],
displayName: { name: 'Frontend', color: 'cyan' },
testEnvironment: 'jsdom',
transform: tsjPreset.transform,
globals: {
'ts-jest': {
tsconfig: {
noPropertyAccessFromIndexSignature: false,
},
},
},
moduleNameMapper: {
'\\.(css|less|scss|sass)$': 'identity-obj-proxy',
},
},
{
testMatch: ['<rootDir>/packages/backend/tests/**/*.(spec|test).*'],
displayName: { name: 'Backend', color: 'blue' },
testEnvironment: 'node',
transform: tsjPreset.transform,
},
],
}
export default config Note - what did the trcik as specifying transform for each project, and not having a top level testRegex etc. Also, although I have tsconfig.json files in each sub-project that extend the baseline one at the monorepo's root, there doesn't appear to be a way to force ts-jest to actually pick these up correctly. Hence the need to override the globals. |
I'm also running into this problem. All my tests are failing after migrating to TypeScript project references. It would be nice to have a fix for this. |
You can use
{
"extends": "../tsconfig.json"
} |
depending on what underlying typescript api e.g. issue: TypeStrong/ts-loader#1005 |
I know this is an old issue, but if anyone else is running into similar problems... globals: {
'ts-jest': {
isolatedModules: true,
},
} |
This, hilariously, just worked for me. What doesn't make sense too is that if I put |
@alexbruno @divmgl this is not a solution, is a workaround with a drawback: you loose type checking |
the more I spend time with this thing, the more I touch its absurdity... nothing seems to be reliably reproducible, and the quality of the reporting/logging is .... .. baffling at best. |
FYI, just open an issue explaining that |
This doesn't solve my problem. When an error occurs in the common module, the correction is not reflected when you correct it and run jest again. |
I was dealing with incorrect path resolution in a monorepo, which I have also been able to solve. My specific problem was: I have multiple packages in my monorepo, and they all map To solve this, I had to create my own resolver, mimicking what TypeScript does, to find the closest
What I've done is the following (assume that my monorepo uses a scope
The following is specific to my situation, but if anyone is still struggling with this, I hope you can use it as an inspiration:
{
"name": "@my/testing",
"version": "0.0.1",
"exports": {
".": "./index.js",
"./resolve": "./resolve.js"
},
"dependencies": {
"fs-extra": "^11.1.1",
"ts-jest": "^29.1.1",
"tsconfig-paths": "^4.2.0"
}
}
const configTemplate = require('./jest.config.template')
function packageConfig(displayName) {
return {
displayName,
...configTemplate
}
}
module.exports = {
packageConfig
}
module.exports = {
preset: 'ts-jest',
transform: {
'^.+\\.tsx?$': [
'ts-jest',
{
isolatedModules: true
}
]
},
testMatch: ['<rootDir>/src/**/*.test.ts'],
resolver: '@my/testing/resolve', // <-- this is where I refer to my resolve script
testEnvironment: 'node'
}
const Path = require('path')
const FS = require('fs')
const tscp = require('tsconfig-paths')
const rootDir = Path.join(__dirname, '../..')
module.exports = function resolve(path, options) {
const { defaultResolver, basedir } = options
if (!path.startsWith('~')) { // <- note, I make a quick check here because I only use the prefix '~' for package-local path resolution
return defaultResolver(path, options)
}
const matchPath = matchPathForSourceFile(basedir)
const matched = matchPath(path, undefined, undefined, options.extensions)
if (matched) {
return defaultResolver(matched, options)
} else {
return defaultResolver(path, options)
}
}
function matchPathForSourceFile(source) {
const dir = closestTSconfigDir(source)
const tsconfig = tscp.loadConfig(dir)
return tscp.createMatchPath(
tsconfig.absoluteBaseUrl,
tsconfig.paths,
tsconfig.mainFields,
tsconfig.addMatchAll
)
}
function closestTSconfigDir(path) {
let dir = Path.dirname(path)
while (dir !== '/') {
if (dir === rootDir) { break }
const tsconfigPath = Path.join(dir, 'tsconfig.json')
if (FS.existsSync(tsconfigPath)) {
return dir
}
dir = Path.dirname(dir)
}
return null
} Now the only thing left to do is adding this packages/package-a$ pnpm add --workspace @my/testing Then, add a
const { packageConfig } = require('@my/testing')
module.exports = packageConfig('@my/package-a') |
oof, just tried updating from TypeScript v5.1.6 to v5.4.5 and ran into this issue. It's odd that project references appear to be working fine with TypeScript v5.1.6 and the following jest.config.ts: {
transform: {
"^.+\\.tsx?$": ["ts-jest", { tsconfig: "tsconfig.test.json" }]
},
} |
🐛 Bug Report
I'm in the process of migrating one of my projects to use Typescript project references, but after migration the tests that validated error types failed.
I've created a repo that has one directory with a very small project where tests succeed, and one directory with a project using typescript projects references where the tests fail. The projects are identical with the exception of project references. I'm not saying that ts-jest is to blame. It could as well be my understanding of project references or jest.
To Reproduce
Expected behavior
I would expect the test to pass, because in the same git repository there is a directory called
works
with an identical project except the project references that has a test that passes.Link to repo (highly encouraged)
https://github.com/FantasticFiasco/jest-error-type-issue
Debug log:
envinfo
The text was updated successfully, but these errors were encountered: