Reputation: 5914
I am trying to create and e2e test for my GraphQL endpoints. After a bit of struggling to let Jest find the tests, I now see that Jest tries to run the tests as JavaScript, not TypeScript. Here is an error output:
SyntaxError: /server/__tests__/users.e2e-spec.ts: Unexpected token, expected ";" (9:10)
7 |
8 | describe('AppController (e2e)', () => {
> 9 | let app: INestApplication
| ^
10 | let apolloClient: ApolloServerTestClient
11 |
12 | beforeEach(async () => {
at Parser.raise (node_modules/@babel/parser/src/parser/location.js:41:63)
at Parser.unexpected (node_modules/@babel/parser/src/parser/util.js:150:16)
at Parser.semicolon (node_modules/@babel/parser/src/parser/util.js:123:40)
at Parser.parseVarStatement (node_modules/@babel/parser/src/parser/statement.js:703:10)
at Parser.parseStatementContent (node_modules/@babel/parser/src/parser/statement.js:216:21)
at Parser.parseStatement (node_modules/@babel/parser/src/parser/statement.js:146:17)
at Parser.parseBlockOrModuleBlockBody (node_modules/@babel/parser/src/parser/statement.js:865:25)
at Parser.parseBlockBody (node_modules/@babel/parser/src/parser/statement.js:841:10)
at Parser.parseBlock (node_modules/@babel/parser/src/parser/statement.js:818:10)
at Parser.parseFunctionBody (node_modules/@babel/parser/src/parser/expression.js:1964:24)
Here is the test script from package.json:
"test:e2e": "jest --config ./tests/jest-e2e.json"
And the Jest config file:
module.exports = {
roots: ['<rootDir>/src'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
}
What am I doing wrong? According to NestJS docs, the tests should run out of the box.
Upvotes: 2
Views: 7624
Reputation: 1701
With configured paths on tsconfig.json
Create jest.config.js on root project folder
const { pathsToModuleNameMapper } = require('ts-jest/utils')
const { compilerOptions } = require('./tsconfig')
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
modulePaths: [
'<rootDir>'
],
}
Upvotes: 2
Reputation: 5914
Following the directions on the ts-jest page solved my problem.
Putting it here incase someone needs it:
Create a jest config:
yarn ts-jest config:init
If you use baseUrl in tsconfig.json, modify the config as below:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
modulePaths: ['<rootDir>/src'],
}
I wish NestJS docs included this. It could save me time.
Upvotes: 10