GithubHelp home page GithubHelp logo

kulshekhar / ts-jest Goto Github PK

View Code? Open in Web Editor NEW
6.8K 35.0 447.0 90.07 MB

A Jest transformer with source map support that lets you use Jest to test projects written in TypeScript.

Home Page: https://kulshekhar.github.io/ts-jest

License: MIT License

JavaScript 10.24% TypeScript 88.26% CSS 1.50%
typescript testing jest

ts-jest's People

Contributors

ahnpnl avatar alan-agius4 avatar alexjoverm avatar bcruddy avatar beckend avatar cspotcode avatar dandv avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar geewee avatar greenkeeper[bot] avatar greenkeeperio-bot avatar gstamac avatar huafu avatar igmat avatar japhar81 avatar joonsungum avatar joscha avatar kulshekhar avatar kwonoj avatar lijunle avatar morajabi avatar renovate[bot] avatar simenb avatar sodatea avatar thymikee avatar tkrotoff avatar tvald avatar whitetrefoil 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  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  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

ts-jest's Issues

Create integration tests with Jest caching enabled

This issue is for tracking of implementation of tests for issue #30.
I'm not sure that I'll be able to complete this task soon, but definitely will try to find a way.
Some thoughts:

  1. Create folder like watch-test;
  2. Create helper like runJestInWatch.ts based on runJest.ts with --watch or --watchAll enabled;
  3. This helper have to do next things:
    3a. Run tests in watch-test and collect results*;
    3b. Change test file in watch-test and collect results*;
    3c. Change source file in watch-test and collect results*;
    3d. Change config file in watch-test and collect results*;
    3e. Terminate process;
  4. Create watch.spec.ts that runs this helpers and checks results for correctness.

* I'm not sure that we'll be able to collect correct results before process termination, so this part could be moved to last step of helper.

TSconfig support

Is it planned? Or there are some restrictions for using more common way for ts developers instead of tweaking package.json?

Can not use module on node v4

You require jest-config, but it's not in the dependency list. If you are using a module, you should always add the dependency on it, because right now you're relying on the flattening behaviour that occurs in NPM v3 (v2 is shipped with node 4). As a result, no one can depend on this module if they are testing on node 4, which is pretty common. See https://travis-ci.org/blakeembrey/node-servie-cors/jobs/198473155 and https://travis-ci.org/blakeembrey/node-servie-cors/jobs/198472981 where I tried to use this module.

Edit: Also a duplicate of #81.

SourceMapConsumer error

Version 0.1.8 works fine, the repo master works.

Version >0.1.8 results in:

      at new SourceMapConsumer (node_modules/source-map-support/node_modules/source-map/lib/source-map-consumer.js:17:22)
      at mapSourcePosition (node_modules/source-map-support/source-map-support.js:164:14)
      at wrapCallSite (node_modules/source-map-support/source-map-support.js:331:20)
      at node_modules/source-map-support/source-map-support.js:366:26
      at Array.map (native)
      at Function.prepareStackTrace (node_modules/source-map-support/source-map-support.js:365:24)
      at process._tickCallback (internal/process/next_tick.js:103:7)

Error reproduce-able in repo branch, CI output.

Reproduce:

  • Clone
  • git checkout ts-jest-source-map-er-1
  • npm -g i jest-cli
  • npm i
  • jest --coverage --no-cache

How to use with target="es6"?

I use https://github.com/s-panferov/awesome-typescript-loader instead of ts-loader, which speeds up compilation.
My current tsconfig.json is:

{
  "compilerOptions": {
    "noEmit": true,
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "jsx": "preserve",
    "lib": ["dom","es5","es6","es7","es2017.object"]
  },
  "filesGlob": [
    "./**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "build"
  ],
  "awesomeTypescriptLoaderOptions": {
    "useBabel": true,
    "forkChecker": true,
    "useCache": false
  }
}

And my jest config is:

  "jest": {
    "collectCoverageFrom": [
      "app/**/*.{js,jsx}",
      "!app/app.js",
      "!app/routes.js"
    ],
    "moduleDirectories": [
      "node_modules",
      "<rootDir>/app"
    ],
    "moduleNameMapper": {
      ".*\\.css$": "<rootDir>/mocks/cssModule.js",
      ".*\\.jpg$": "<rootDir>/mocks/image.js",
      ".*\\.svg$": "<rootDir>/mocks/svg.js"
    },
    "setupTestFrameworkScriptFile": "<rootDir>/internals/testing/test-bundler.js",
    "testRegex": "tests/.*\\.test\\.(ts|tsx|js)$",
    "transform": {
      ".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "json"
    ]
  }

So my tests obviously fail with SyntaxError: Unexpected token import.
How to handle this setup with ts-jest?

node: v.6.6.0
typescript: 2.0.8
ts-jest: 17.0.0

Enable zero-config

I think the next major feature for this package is enabling zero-config like it works with babel-jest package.
After some investigation I've found that babel-jest is enabled without any extra config because of implementation of jest.

So only option to provide the best experience for our users is creating issue and PR in Jest repo and hoping that it will be accepted ๐Ÿ˜„

But it seems to me that before that we have to refactor current project and cover it by tests as close to 100% as possible.

Support for "jsx": "preserve" config

After issue #58 I've realized that we have no support for this options in config which leads to errors that user can't understand.
Possible solutions:

  1. Find a way to activate babel-jest transformer from jest config after ts-jest applied.
  2. Inform user that this option is not allowed and use "jsx": "react" instead.
  3. Include babel-jest transformer in our package and run it if "jsx": "preserve" is used.

As for me third solution seems to be the worst.
First of all we have to create tests for this case.

coverageprocessor breaks when jest is not run with --no-cache

The cache is written to global when the preprocessing happens, but preprocessing is skipped when possible if --cache is enabled (and it is by default).

As the preprocessor does set up the mapping data structures, but just writes nothing into it, there will be an exception thrown in remap-istanbul for each of the input files.

Missing modules

`As of version 0.1.9.
Running jest: Cannot find module 'jest-config'.

With testprocessor: "istanbul-lib-instrument" module is missing.

How to debug with vscode?

I added ts-jest to my project and the tests work fine (thx for that by the way! ๐Ÿ˜€ )

Unfortunately, I cannot properly debug the tests in vscode. I added the following launch config:

    {
      "name": "Tests",
      "type": "node",
      "request": "launch",
      "program": "${workspaceRoot}/node_modules/jest-cli/bin/jest.js",
      "stopOnEntry": false,
      "args": ["--runInBand", "--no-cache"],
      "cwd": "${workspaceRoot}",
      "preLaunchTask": null,
      "runtimeExecutable": null,
      "runtimeArgs": [
          "--nolazy"
      ],
      "env": {
          "NODE_ENV": "development"
      },
      "console": "internalConsole",
      "sourceMaps": true,
      "outDir": "${workspaceRoot}/dist/"
    },

I can run this config but vscode ignores all breakpoints. It complains:

Breakpoint ignored because generated code not found (source map problem?).

Any ideas?

The watched jest tests with results remapping fail.

Hi guys,

I am facing an issue with failing watcher when I use jest with ts-jest and turned on remapping witch option "testResultsProcessor": "<rootDir>/node_modules/ts-jest/coverageprocessor.js". If I run the jest with jest --coverage --watch -i --no-cache the watcher fails after first rune with an error:

0 info it worked if it ends with ok
1 verbose cli [ 'C:\Program Files\nodejs\node.exe',
1 verbose cli 'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js',
1 verbose cli 'run',
1 verbose cli 'watch-test',
1 verbose cli '--',
1 verbose cli '--verbose' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prewatch-test', 'watch-test', 'postwatch-test' ]
5 info lifecycle @1.0.0prewatch-test: @1.0.0
6 silly lifecycle @1.0.0
prewatch-test: no script for prewatch-test, continuing
7 info lifecycle @1.0.0watch-test: @1.0.0
8 verbose [email protected]
watch-test: unsafe-perm in lifecycle true
9 verbose lifecycle @1.0.0watch-test: PATH:
10 verbose lifecycle @1.0.0
watch-test: CWD:
11 silly lifecycle @1.0.0watch-test: Args: [ '/d /s /c', 'npm run test -- --watch "--verbose"' ]
12 silly lifecycle @1.0.0
watch-test: Returned: code: 1 signal: null
13 info lifecycle @1.0.0~watch-test: Failed to exec watch-test script
14 verbose stack Error: @1.0.0 watch-test: npm run test -- --watch "--verbose"
14 verbose stack Exit status 1
14 verbose stack at EventEmitter. (C:\Program Files\nodejs\node_modules\npm\lib\utils\lifecycle.js:255:16)
14 verbose stack at emitTwo (events.js:106:13)
14 verbose stack at EventEmitter.emit (events.js:191:7)
14 verbose stack at ChildProcess. (C:\Program Files\nodejs\node_modules\npm\lib\utils\spawn.js:40:14)
14 verbose stack at emitTwo (events.js:106:13)
14 verbose stack at ChildProcess.emit (events.js:191:7)
14 verbose stack at maybeClose (internal/child_process.js:877:16)
14 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:226:5)
15 verbose pkgid @1.0.0
16 verbose cwd
17 error Windows_NT 6.1.7601
18 error argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "run" "watch-test" "--" "--verbose"
19 error node v6.9.2
20 error npm v3.10.9
21 error code ELIFECYCLE
22 error @1.0.0 watch-test: npm run test -- --watch "--verbose"
22 error Exit status 1
23 error Failed at the @1.0.0 watch-test script 'npm run test -- --watch "--verbose"'.
23 error Make sure you have the latest version of node.js and npm installed.
23 error If you do, this is most likely a problem with the package,
23 error not with npm itself.
23 error Tell the author that this fails on your system:
23 error npm run test -- --watch "--verbose"
23 error You can get information on how to open an issue for this project with:
23 error npm bugs
23 error Or if that isn't available, you can get their info via:
23 error npm owner ls
23 error There is likely additional logging output above.
24 verbose exit [ 1, true ]

If I try to remove "testResultsProcessor" the watched test is working.

If I try to comment out lines (38-41) in coverageprocessor.js the watched test is working as well.

The only workaround I found is running coverage on demand separately (out of watched test). It makes sense but finding it out took some time.

Maybe you will find a way how to fix it and if not others will find a way how to mitigate it earlier than me.

How to display remapped coverage report in the terminal?

I apologize if I'm missing something obvious or if I'm repeating this issue.

Current Behavior

The remapped coverage works in the browser:

screen shot 2017-01-24 at 3 58 48 pm
screen shot 2017-01-24 at 3 55 43 pm

The terminal is displaying the unmapped coverage, look at "branch" and "uncovered lines":

screen shot 2017-01-19 at 3 12 28 pm

jest config in package.json

screen shot 2017-01-25 at 12 07 58 pm

Desired Behavior

Remapped coverage displays in the terminal.

What am I missing?
Thanks in advance.

Appveyor support

@kulshekhar, please contact me via email. We have to add webhook to repo settings in order to run builds on appveyor(Windows testing) when something pushed.
Plus, it would be great, if you take a look at appveyor.yml, because our builds failed when they don't have to.

Source with TS

@kulshekhar , is reworking of package sources from vanilla JS to TS acceptable? It'll provide us with easier maintain process I guess.

Tests are reported twice - once for .ts and once for .js file

I am new to Jest and relatively new to TypeScript and have setup my ts-jest by following this guide.

My first test file looks like this:

    describe("It works", () => {
        it("is true", () => {
            expect(2).toBeTruthy();
        });
    });

When I run the test script from my package.json the output is as follows:

 PASS  dist\common\__tests__\sample.jest.test.js
 PASS  src\common\__tests__\sample.jest.test.ts

Test Suites: 2 passed, 2 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.767s, estimated 2s
Ran all test suites.

My tsconfig.json looks like this:

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es6",
        "jsx": "react"
    },
    "include": [
        "./src/**/*"
    ],
    "lib": [
        "dom", "es6", "dom.iterable", "scripthost", "ES2015.Iterable", "ES2015.Promise"
    ]
}

The jest section of my package.json looks like this:

  "jest": {
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "transform": {
      "\\.(ts|tsx)$": "./node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "/__tests__/.*\\.(ts|tsx|js)$"
  },

The versions in use are:
TypeScript 2.1.5
ts-jest 18.0.2
jest 18.1.0
node 6.9.1

Is this expected behaviour?
It would be manageable for when all the tests pass, but failures are also reported twice: once for the original .ts and once for the transpiled .js.

Am I doing something wrong?

[React-Native] SyntaxError: Unexpected token import

package.json: https://gist.github.com/Lxxyx/b8d343e17b521182d61515cdbc15c5bb
tsconfig.json: https://gist.github.com/Lxxyx/88acca172a37fada578e98af3b072452

ReactNative Version: 0.40
system: Mac 10.12
node: v6.9.1

Question: run jest, get unexpected token import error.

error:

FAIL src/model/tests/schedule.test.ts
โ— Test suite failed to run

/Users/lxxyx/Desktop/app/iNCU/src/model/__tests__/schedule.test.ts:9
import scheduleModel from '../schedule';
^^^^^^
SyntaxError: Unexpected token import

  at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
  at handle (node_modules/worker-farm/lib/child/index.js:41:8)
  at process.<anonymous> (node_modules/worker-farm/lib/child/index.js:47:3)
  at emitTwo (events.js:106:13)

Coverage

Coverage is successfully generated but i don't think the line numbers are correct at all.
jest issue 1907.

ts-jest breaks strict mode

The preprocessor prepends require('ts-jest').install(); to the resulting source code, which makes any possible "use strict" no longer a directive.

Coverage difference while targeting ES5 and ES6

@kwonoj could you, please, explain this strange behavior? When tsc targets ES6 we have this output in coverage.txt:

-----------|----------|----------|----------|----------|----------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
-----------|----------|----------|----------|----------|----------------|
 simple\   |    85.71 |    33.33 |       75 |    85.71 |                |
  Hello.ts |    85.71 |    33.33 |       75 |    85.71 |             20 |
-----------|----------|----------|----------|----------|----------------|
All files  |    85.71 |    33.33 |       75 |    85.71 |                |
-----------|----------|----------|----------|----------|----------------|

But when we targeting ES5 output is changed to this:

-----------|----------|----------|----------|----------|----------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
-----------|----------|----------|----------|----------|----------------|
 simple\   |    90.91 |       50 |       80 |    88.89 |                |
  Hello.ts |    90.91 |       50 |       80 |    88.89 |             20 |
-----------|----------|----------|----------|----------|----------------|
All files  |    90.91 |       50 |       80 |    88.89 |                |
-----------|----------|----------|----------|----------|----------------|

Is this expected and normal or something goes wrong with our remapping mechanism?

[ERROR] Unknown config option "transform" on jest v0.17

โ— The settings `scriptPreprocessor` and `preprocessorIgnorePatterns` were replaced 
  by `transform` and `transformIgnorePatterns` which support multiple preprocessors.

  Jest now treats your current settings as:

    "transform": {".*": "./node_modules/ts-jest/preprocessor.js"}

Error: Unknown config option "transform" with value "[object Object]". This is either 
a typing error or a user mistake and fixing it will remove this message.

I don't sure this is an error message from jest or ts-jest. But most of my test suites are written in TypeScript, so I think that I will post this issue here.

Node v7.0
Jest v0.17

Type error reporting

Currently it seems that the preprocessor doesn't report type errors. Would it be possible to treat type errors in TS files (whether source or test files) as if they were test failures?

"Error: Could not find source map for ..." always when used without --no-cache

I'm getting this error for every file, every time I try to use jest with ts-jest:

Error: Could not find source map for: "/Users/nixin/Documents/Projects/aurelia/skeleton-navigation/skeleton-typescript-webpack-experimental/src/app.ts"
    at /Users/nixin/Documents/Projects/aurelia/skeleton-navigation/skeleton-typescript-webpack-experimental/node_modules/remap
-istanbul/lib/remap.js:257:11
    at Array.forEach (native)
    at /Users/nixin/Documents/Projects/aurelia/skeleton-navigation/skeleton-typescript-webpack-experimental/node_modules/remap
-istanbul/lib/remap.js:214:22
    at Array.forEach (native)
    at remap (/Users/nixin/Documents/Projects/aurelia/skeleton-navigation/skeleton-typescript-webpack-experimental/node_module
s/remap-istanbul/lib/remap.js:213:12)
    at processResult (/Users/nixin/Documents/Projects/aurelia/skeleton-navigation/skeleton-typescript-webpack-experimental/nod
e_modules/ts-jest/dist/coverageprocessor.js:29:29)
    at source.getTestPaths.then.then.then.runResults (/Users/nixin/.yarn-config/global/node_modules/jest-cli/build/jest.js:206
:9)

If I use jest --no-cache there is no error.

Any ideas?

It generates remapped coverage only for main.ts

I have a Typescript project and I'm facing issues generating the remapped coverage.
It creates only the coverage for main.ts instead that for all the files - the original coverage has all the files (but with wrong lines, of course).

This is the relevant part of my package.json:

{
  "watch": {
    "pretest": {
      "patterns": "src",
      "extensions": "ts"
    },
    "start": {
      "patterns": "src",
      "extensions": "ts"
    }
  },
  "scripts": {
    "prestart": "tsc && ./scripts/localModuleUpdate.sh",
    "start": "node dist/main",
    "pretest": "tslint 'src/**/*.ts'; echo",
    "test": "jest",
    "watch": "npm-watch",
    "postinstall": "typings install && ./scripts/localModuleUpdate.sh",
    "coverage": "jest --no-cache --coverage"
  },
  "dependencies": {
    "body-parser": "^1.15.2",
    "cors": "^2.8.1",
    "csv": "^1.1.0",
    "express": "^4.14.0",
    "lodash": "^4.17.2",
    "mongoose": "^4.7.4",
    "typescript": "^2.1.4",
    "validator": "^6.2.1"
  },
  "devDependencies": {
    "jest": "^18.0.0",
    "npm-watch": "^0.1.6",
    "sinon": "^1.17.7",
    "supertest": "^2.0.1",
    "ts-jest": "^18.0.2",
    "tslint": "^4.1.1",
    "typings": "^2.1.0"
  },
  "jest": {
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "transform": {
      "^.+\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "/__tests__/.*\\.(ts|tsx)$",
    "testResultsProcessor": "<rootDir>/node_modules/ts-jest/coverageprocessor.js",
    "collectCoverageFrom": [
      "src/**/*.tsx",
      "src/**/*.ts"
    ],
  }
}

and this is tsconfig.json:

{
  "compilerOptions": {
    "module": "CommonJS",
    "target": "ES6",
    "noResolve": false,
    "noImplicitAny": false,
    "strictNullChecks": true,
    "noUnusedParameters": true,
    "noUnusedLocals": true,
    "outDir": "dist"
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.d.ts",
    "typings/**/*.d.ts"
  ],
  "exclude": [
    "src/f-*/*"
  ]
}

I run the tests with:

npm coverage

Any suggestion?

Tests with TS.

Just the same as was with sources. It always easier to develop and test with TS than with vanilla JS.

JSX: Unexpected token

hi!

I'm using example of 'jest' configuration from readme.md and this simple test

const renderer = require('react-test-renderer')

it('renders correctly', () => {
  const tree = renderer.create(<div>hi!</div>).toJSON()
  expect(tree).toMatchSnapshot()
})

gives the next Error:

   var tree = renderer.create(<div>hi!</div>).toJSON();
                                   ^
    SyntaxError: Unexpected token <

      at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:285:10)
      at process._tickCallback (internal/process/next_tick.js:103:7)

Any ideas? I'd be grateful.

Node.js 4 support

Working on issue #35 I've realized that our package doesn't support Node.js 4 (at least it doesn't correctly tested under this version). But Jest supports it, so we have to provide our users with such compatibility.

Cache support

As for now cache is disabled. But it seems that it would greatly increase performance, because of omitting of unnecessary transpilations.
We are able to cache next stuff:

  1. tsconfig in order to avoid extra disc I/O. It could be easily implemented in transpile-if-ts.ts or in utils.ts. But how to handle its changes during test running? And should we handle them, cause it doesn't seems to be common operation?
  2. All other configs could be cached as tsconfig I guess, but it needs further investigation. @kwonoj you probably know this better, any thoughts?
  3. sourceMapCache is easily provided by false value of options.emptyCacheBetweenOperations and may be with using of options.hookRequire = true;(but I'm not sure about this option) in index.ts.
  4. Providing fileContentsCache could be problematic. On one hand it seems that we are able to easily implement it in our default-retrieve-file-handler.ts, but on other hand it won't be the same thing as sourceMapCache from source-map-support, because the last one isn't exported, so we have no access to it, more of that: it appears in a lot of different places through source-map-support.js, so two caches could be mis-synchronized and produce a lot of mistakes.

And at last, we have to find a way how to test that all this stuff works correctly and may be that it really improves performance. I guess, we could run jest process in our integration test with --watchAll flag and rewrite .ts, .tsx and .json files using fs, but I'm not sure that it is a good solution and even that it would work correctly.

Support for imports with absolute path

Due to issue #58 I found out that unfortunately imports like

import { reposLoaded, repoLoadingError } from 'containers/App/actions';

don't work with jest and produces next error:

app\containers\HomePage\tests\sagas.test.ts
  โ— Test suite failed to run

    Cannot find module 'containers/App/actions' from 'sagas.ts'

      at Resolver.resolveModule (node_modules\jest-resolve\build\index.js:151:17)
      at Object.<anonymous> (app\containers\HomePage\sagas.ts:8:19)
      at Object.<anonymous> (app\containers\HomePage\tests\sagas.test.ts:7:17)

While normal imports with relative paths behave as expected. It could be problem of jest-resolve module, but we have to try to solve it inside ts-jest or find what exactly causes this problem in jest-resolve.
As always we have to start from tests for this case.

__TC_CONFIG__ in package.json jest.globals

node: v6.8.0
jest: v16.0.1
ts-jest: 0.1.7

First of all, thank you for this package, it saves me alot!

I spotted a bug (or did I miss anything?):
If __TC_CONFIG__ doesn't appear in package.json, the line number mapping won't pass to stack trace messages.

To reproduce this, delete the __TC_CONFIG__ section in tests/simple/package.json and under dir tests/simple run jest:

 FAIL  __tests__/Hello.test.ts
  โ— Hello Class โ€บ should throw an error on line 11

    Hello error!

      at new Hello (Hello.ts:5:15)
      at Object.<anonymous> (__tests__/Hello.test.ts:5:21)

  Hello Class
    โœ• should throw an error on line 11 (7ms)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.918s, estimated 1s
Ran all test suites.

Note that the line at new Hello (Hello.ts:5:15) was at new Hello (Hello.ts:11:15) before changing package.json

However if I add the __TS_CONFIG__:{} back into config, everything is working normal:

 FAIL  __tests__/Hello.test.ts
  โ— Hello Class โ€บ should throw an error on line 11

    Hello error!

      at new Hello (Hello.ts:11:11)
      at Object.<anonymous> (Hello.test.ts:9:19)

  Hello Class
    โœ• should throw an error on line 11 (113ms)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.973s, estimated 1s
Ran all test suites.

If I understand correctly, __TC_CONFIG__ is mean to override tsconfig settings, so we should expect ts-jest works out-of-box without providing a __TC_CONFIG__?

Could not find source map for

I get this error when running coverage on my test project. I imagine it's because I'm using outdir, and am outputting everything to ./dist

Is there a way to specify that as an option?

Error: Could not find source map for: ...

Coverage Report - incorrect lines

The function beginning at line 3 is not covered by my test suite, however the code coverage report gives me seemingly arbitrary line numbers.

1  render() {
2   // TODO: remove copy (for hot reloading)
3    const handleDivClick1 = () => {     // NOT COVERED
4      console.log('click!');
5      this.setState({
6        name: 'John'
7      });
8    };
9    return (
10     // TODO: replace onClick with class member (for hot reloading)
11     <div className={styles.color} onClick={this.handleDivClick}>{`Name: ${this.state.name}`}</div>
12   );
13 }
14}

The coverage report says that lines 10,11 are not covered, though even that changes depending on how many blank lines are included in the component.

Let me know if I can provide further information.
Cheers,
Tyler

EDIT: The reports with coverage/remapped are correct, it's just the console output and reports within coverage/lcov-report that are incorrect.

Error When Including Module From Mapped Path

Hi there, I'm getting an error when trying to load a module from a mapped path. The error is as follows:

    Cannot find module '@app/constants/actionTypes' from 'index.ts'
      
      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:151:17)
      at Object.<anonymous> (src/actions/auth/index.ts:3:69)
      at Object.<anonymous> (src/actions/auth/spec.ts:4:15)

And I'm trying to do the following:

import * as actionTypes from "@app/constants/actionTypes";

The file definitely exists and worked with relative paths.

Here's my tsconfig.json:

{
    "compilerOptions": {
        "outDir": "./dist/",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es5",
        "jsx": "react",
        "baseUrl": ".",
        "paths": {
            "@app/*": [ "./src/*" ]
        }
    },
    "filesGlob": [
        "src/**/*.ts",
        "src/**/*.tsx",
        "src/*.ts",
        "src/*.tsx"
    ],
    "exclude": [
        "node_modules"
    ]
}

And here's the jest configuration of package.json;

  "jest": {
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "transform": {
      ".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testResultsProcessor": "<rootDir>/node_modules/ts-jest/coverageprocessor.js",
    "testRegex": "(/test/.*|(test|spec))\\.(ts|tsx)$",
    "collectCoverage": true,
    "collectCoverageFrom": [
      "src/**/*.{ts,tsx}"
    ],
    "moduleDirectories": [
      "node_modules",
      "src"
    ]
  }

As you can see, I'm including the moduleDirectories, as suggested.

What's weirder still, is that I can still reference other modules through that path, and the following runs without error:

import { RequestLogin, ResponseError, ResponseAuth } from "@app/models/api";

Compiling directly with tsc and with the --traceResolution flag it seems to resolve without issue:

======== Resolving module '@app/constants/actionTypes' from '/var/www/front-end/src/actions/auth/index.ts'. ========
'baseUrl' option is set to '/var/www/front-end', using this value to resolve non-relative module name '@app/constants/actionTypes'
'paths' option is specified, looking for a pattern to match module name '@app/constants/actionTypes'.
Module name '@app/constants/actionTypes', matched pattern '@app/*'.
Trying substitution './src/*', candidate module location: './src/constants/actionTypes'.
Loading module as file / folder, candidate module location '/var/www/front-end/src/constants/actionTypes'.
File '/var/www/front-end/src/constants/actionTypes.ts' exist - use it as a name resolution result.
Resolving real path for '/var/www/front-end/src/constants/actionTypes.ts', result '/var/www/front-end/src/constants/actionTypes.ts'
======== Module name '@app/constants/actionTypes' was successfully resolved to '/var/www/front-end/src/constants/actionTypes.ts'. ========

It's baffling me as I can't work out why it would affect one module, but not the other.

Thanks for your help.

Using Babel as secondary compiler

Due to lack of support for some features of es6/es7 in Typescript I have to use Typescript + Babel compiling chain. But even if I can make tests with this chain, coverage is not correct. Can the babel be implemented as a secondary optional compiler with proper istanbul remapping?

Package versioning

@kulshekhar I have a proposal for our package.
After check of issue #56 I've found that problem is caused by our dependencies.
While jest is in peerDependencies we have jest-config and jest-util as dependencies. We probably could remove them, because they are included by jest, so we will always use user version of this packages based on what version of jest he installed.
But it will work normally only in case when jest haven't introduce some breaking changes. And because of that user have to carefully search for version of our package that works with his version of jest, and for now it's really difficult to accomplish.
In order to simplify this process, we could use same major and minor number from jest package and patch number for fixes of ts-jest. What do you think about this?

Should this work with react native?

I'm using jest and react native. I can test it by manually compiling the typescript into js and running jest on that. Trying to use this project I get

/node_modules/react-native/jest/setup.js:40
      )
      ^
    SyntaxError: Unexpected token )
      
      at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
      at handle (node_modules/worker-farm/lib/child/index.js:41:8)
      at process.<anonymous> (node_modules/worker-farm/lib/child/index.js:47:3)
      at emitTwo (events.js:106:13)

My relevant package.json

  "jest": {
    "preset": "react-native",
    "setupFiles": [
      "./jest/setup.js"
    ],
    "transform": {
      ".(ts|tsx)": "./node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ]
  }

I've read through the limitations but those don't seem to apply to me, not targeting ES6 ect. Using node v6.9.2

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.