I am having issues setting up Jest with typescript. I keep getting the same error no matter what settings I change in jest.config.js
Here are my config files
//jest.config.js
module.exports = {
collectCoverage: false,
moduleDirectories: ['node_modules', '<rootDir>/'],
moduleNameMapper: {
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
'^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js',
'^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i': `<rootDir>/__mocks__/fileMock.js`,
// Handle module aliases
// Should also be updated in tsconfig.json
"#lib/*": ["<rootDir>/app/lib/*"]
},
preset: 'ts-jest',
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
testEnvironment: 'node',
transform: {
"^.+\\.tsx?$": "ts-jest"
},
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']
}
This is my jest.config.ts file
import '#testing-library/jest-dom/extend-expect'
This is my test file:
test("auth test", async () => {
const auth = await authenticate("invaild", "password")
expect(auth).toBe(false);
});
The error is thrown in the authenicate function from import PocketBase from "pocketbase";
This is the error produced:
SyntaxError: Unexpected token 'export'
4 | // This file sets up the connection to the database
5 |
> 6 | import PocketBase from "pocketbase";
| ^
7 |
8 | export function DBConnection(): PocketBase {
9 | if (process.env.DB_PORT === undefined) {
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1598:14)
Related
Getting ReferenceError: You are trying to import a file after the Jest environment has been torn down From office/test/office.test.ts.
Used jest.useFakeTimers(); after imports, but the issue still exists. Is there any way to resolve it ?
Here is my jest.config.ts
import type { Config } from "#jest/types"
const config: Config.InitialOptions = {
transform: {
'^.+\\.tsx?$': 'ts-jest'
},
testRegex: '(/__test__/.*|(\\.|/)(test|spec))\\.[jt]sx?$',
moduleFileExtensions: [ 'js','ts'],
testEnvironment: "jest-environment-node",
fakeTimers: {
enableGlobally: true,
},
verbose: true
}
export default config
The test file office.test.ts
import {ApolloServer} from 'apollo-server'
import {expect,test,jest} from '#jest/globals';
import officeGql from '../controllers/controller'
jest.useFakeTimers();
test('Office Module Test', async () => {
let typeDefs = officeGql.types
let resolvers = officeGql.resolvers
let testServer = new ApolloServer({
typeDefs,
resolvers,
});
const response = await testServer.executeOperation({
query: `query offices(limit: $limit,offset: $offset){name, address}`,
variables: { limit: 10,offset:0 },
});
expect(response.data).toBeTruthy();
});
I use Inertia, Vue3, and Vite as bundling assets. When I set up and run with SSR in nodejs the error always appears Unknown file extension ".vue". I've been googling for days but haven't solved it.
This is my ssr.js file which I run with nodemon
import { createSSRApp, h } from 'vue'
import { renderToString } from '#vue/server-renderer'
import { createInertiaApp } from '#inertiajs/inertia-vue3'
import createServer from '#inertiajs/server'
createServer.default((page) => createInertiaApp({
page,
render: renderToString,
resolve: async (name) => {
return (await import(`./Pages/${name}.vue`)).default;
},
setup({ app, props, plugin }) {
return createSSRApp({
render: () => h(app, props),
}).use(plugin)
},
}))
vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
// import react from '#vitejs/plugin-react';
import vue from '#vitejs/plugin-vue';
export default defineConfig({
plugins: [
laravel({
input: 'resources/js/app.js',
ssr: 'resources/js/ssr.mjs',
}),
// react(),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
],
ssr: {
noExternal: ['#inertiajs/server'],
},
resolve: {
alias: {
'#': '/resources/js'
}
}
});
when I run it with nodemon ssr.js an error like this will appear
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".vue" for C:\Users\USER\Documents\biviplant\biviplant\resources\js\Pages\Test.vue
When I run the e2e test(as integration tests) I get a getRepository null error. I import the entire app module in my test spec file(below),the error occurs, which says something like this:
[Nest] 47867 - 08/22/2022, 8:07:35 PM ERROR [ExceptionsHandler] Cannot read property 'getRepository' of null
TypeError: Cannot read property 'getRepository' of null
TypeError: Cannot read property 'getRepository' of null
at new usersService (/mypath/src/users/users.service.ts:35:42)
at Injector.instantiateClass (/mypath/node_modules/#nestjs/core/injector/injector.js:330:19)
at callback (/mypath/node_modules/#nestjs/core/injector/injector.js:48:41)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at Injector.loadInstance (/mypath/node_modules/#nestjs/core/injector/injector.js:52:9)
at Injector.loadProvider (/mypath/node_modules/#nestjs/core/injector/injector.js:74:9)
at Injector.resolveComponentHost (/mypath/node_modules/#nestjs/core/injector/injector.js:192:13)
at async Promise.all (index 0)
at Injector.loadCtorMetadata (/mypath/node_modules/#nestjs/core/injector/injector.js:358:23)
at Injector.resolveConstructorParams (/mypath/node_modules/#nestjs/core/injector/injector.js:89:26)
FAIL test/user.service.int-spec.ts (10.525 s)
GET /users
✓ (GET) / (102 ms)
✕ (GET) /users (62 ms)
● GET /users › (GET) /users
expected 200 "OK", got 500 "Internal Server Error"
26 |
27 | it('(GET) /users', () => {
> 28 | return request(app.getHttpServer()).get('/users').expect(200);
| ^
29 | });
30 | });
31 |
at Object.<anonymous> (test/user.service.int-spec.ts:28:59)
----
at Test._assertStatus (node_modules/supertest/lib/test.js:252:14)
at node_modules/supertest/lib/test.js:306:17
at Test._assertFunction (node_modules/supertest/lib/test.js:285:13)
at Test.assert (node_modules/supertest/lib/test.js:164:23)
at Server.localAssert (node_modules/supertest/lib/test.js:120:14)
The folder structure is this:
parent_folder
| package.json
| package-lock.json
| ---src
| \-User
| \-user.module.ts
| \-user.service.ts
| \-user.controller.ts
|...
| ---tests
| \-jest-int.json
| \-user.int-spec.ts
The jest config file contains this:
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": "../", // <<<--- I use absolute path path, so rootDir is "../"
"roots": ["<rootDir>"],
"modulePaths": ["<rootDir>"],
"moduleDirectories": ["node_modules"],
"testEnvironment": "node",
"testRegex": ".int-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
The module contains this only:
import { Module } from '#nestjs/common';
import { UsersController } from './Users.controller';
import { UsersService } from './Users.service';
#Module({
providers: [UsersService],
controllers: [UsersController],
})
export class UserModule {}
The service contains:
#Injectable()
export class UsersService {
private userRepository: Repository<User>;
private fileRepository: Repository<file>;
private filedworthRepository: Repository<filedworth>;
private filedValueRepository: Repository<filedValue>;
private fileStrategyRepository: Repository<fileStrategy>;
private valueRepository: Repository<Value>;
private defaultData = {
created_date: new Date(),
updated_date: new Date(),
created_by: 'user',
updated_by: 'user',
};
constructor(#Inject(CONNECTION) private connection: DataSource) {
this.userRepository = connection.getRepository(user);
this.fileRepository = connection.getRepository(file);
this.filedworthRepository =
connection.getRepository(filedworth);
this.filedValueRepository =
connection.getRepository(filedValue);
this.fileStrategyRepository =
connection.getRepository(fileStrategy);
this.ValueRepository = connection.getRepository(Value);
}
...//other methods
}
The controller is:
#Controller('users')
export class usersController {
constructor(private usersService: usersService) {}
#Get()
getusers(
#Query()
query: GetUsersFilterDto,
) {
return this.usersService.getusers(query);
}
...//others
}
and the test file itself contains the following:
import { Test, TestingModule } from '#nestjs/testing';
import { INestApplication } from '#nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('GET /users ', () => {
let app: INestApplication;
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
afterAll(async () => {
await app.close();
});
it('(GET) /', () => {
return request(app.getHttpServer()).get('/').expect(200);
});
it('(GET) /users', () => {
return request(app.getHttpServer()).get('/users').expect(200);
});
});
I run the test using:
npm run test:int // "test:int": "jest -i --no-cache --detectOpenHandles --config ./test/jest-int.json"
Is there something I'm missing? Hopefully these are enough details to convey my issue.
You need to add CONNECTION as a provider to your test app: TestingModule =
await Test.createTestingModule({
imports: [AppModule],
providers: [
{ provide: CONNECTION, getRepository: jest.fn() },
],
}).compile();
What Georgi has mentioned was true, I hadn't provided the values of the dependency CONNECTION that was being injected. But, the syntax mentioned there didn't work, this did:
beforeAll(async () => {
const connection = await DataSource(myDB_Config);//hosturl, port etc.
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
})
.overrideProvider(CONNECTION)
.useValue(connection)
.compile();
app = moduleFixture.createNestApplication();
await app.init();
});
I have a simple AWS Lambda function (state-info.ts) which I am tree-shaking with Rollup and it is giving me the following error:
[!] Error: 'DB' is not exported by ../../forest-fire/abstracted-admin/lib/index.js
https://github.com/rollup/rollup/wiki/Troubleshooting#name-is-not-exported-by-module
src/state-info.ts (10:9)
8: import { Lambda } from "aws-sdk";
9: import { STATES } from "./models/shared";
10: import { DB } from "abstracted-admin";
^
11: import { StateInfo } from "./models/StateInfo";
12: import { IApiResponse } from "./shared/ApiRetriever";
Now it just so happens that I wrote the module abstracted-admin (currently at v0.6.5 on npm) which it is complaining about and it DOES export DB as a named export (and as the default export). But for some reason Rollup is unhappy.
I've created a video walk-through of everything for full context: video.
For those of you who don't like video, here are the key facts/files:
abstracted-admin/lib/index.d.ts:
import { DB } from "./db";
export default DB;
export { DB, IFirebaseConfig, IFirebaseListener } from "./db";
abstracted-admin/lib/index.js:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const db_1 = require("./db");
exports.default = db_1.DB;
var db_2 = require("./db");
exports.DB = db_2.DB;
and from within the abstracted-admin/package.json:
{
...
"files": ["lib"],
"main": "lib/index.js",
"typings": "lib/index.d.ts",
}
state-info.ts (aka, the file being rolled up):
import {
IDictionary,
AWSGatewayCallback,
IAWSGatewayRequest,
IAWSGatewayResponse
} from "common-types";
import GetStateInfo from "./vote-smart/get-state-info";
import { Lambda } from "aws-sdk";
import { STATES } from "./models/shared";
import { DB } from "abstracted-admin";
import { StateInfo } from "./models/StateInfo";
import { IApiResponse } from "./shared/ApiRetriever";
/** ... */
Meanwhile my rollup config is:
import cjs from "rollup-plugin-commonjs";
import resolve from "rollup-plugin-node-resolve";
import json from "rollup-plugin-json";
import ts from "rollup-plugin-typescript2";
import globals from "rollup-plugin-node-globals";
export default {
input: "src/state-info.ts",
output: {
file: "lib/state-info-rolled.js",
format: "cjs"
},
external: ["aws-sdk"],
plugins: [
globals(),
json(),
cjs({
include: "node_modules/**",
exclude: ["node_modules/aws-sdk/**"]
}),
ts(),
resolve({
jsnext: true,
main: true,
browser: false,
preferBuiltins: false,
extensions: [".js", ".json"]
})
]
};
I believe Rollup expects the below in this situation:
import admin from "abstracted-admin";
const { DB } = admin;
It's different from Webpack's behavior and has caught me a few times.
I'm having a testsuite which I'm now trying to test via CI. (Bamboo)
The problem is that this is fully functional on my local system, but wen I deploy it to the Bamboo server (which I cannot configure myself) the call npm --harmony test (--harmony to use const while use strict) fails.
Next, it returns the following errormessage
07-Oct-2016 16:37:03 07 10 2016 16:37:03.315:ERROR [preprocessor.rollup]: Could not resolve '../../services/apicaller.service' from /opt/bamboo-home/xml-data/build-dir/MCAE-MANCAVE-JOB1/src/pages/events/events.component.ts
07-Oct-2016 16:37:03 at /opt/bamboo-home/xml-data/build-dir/MCAE-MANCAVE-JOB1/config/karma-shim.ts
07-Oct-2016 16:37:03 Error: Could not resolve '../../services/apicaller.service' from /opt/bamboo-home/xml-data/build-dir/MCAE-MANCAVE-JOB1/src/pages/events/events.component.ts
07-Oct-2016 16:37:03 at Error (native)
07-Oct-2016 16:37:03 at /opt/bamboo-home/xml-data/build-dir/MCAE-MANCAVE-JOB1/node_modules/rollup-plugin-node-resolve/dist/rollup-plugin-node-resolve.cjs.js:78:21
07-Oct-2016 16:37:03 at /opt/bamboo-home/xml-data/build-dir/MCAE-MANCAVE-JOB1/node_modules/browser-resolve/index.js:265:24
07-Oct-2016 16:37:03 at /opt/bamboo-home/xml-data/build-dir/MCAE-MANCAVE-JOB1/node_modules/resolve/lib/async.js:55:18
07-Oct-2016 16:37:03 at load (/opt/bamboo-home/xml-data/build-dir/MCAE-MANCAVE-JOB1/node_modules/resolve/lib/async.js:69:43)
07-Oct-2016 16:37:03 at onex (/opt/bamboo-home/xml-data/build-dir/MCAE-MANCAVE-JOB1/node_modules/resolve/lib/async.js:92:31)
07-Oct-2016 16:37:03 at /opt/bamboo-home/xml-data/build-dir/MCAE-MANCAVE-JOB1/node_modules/resolve/lib/async.js:22:47
where ../../services/apicaller.service is an import statement in src/pages/events/events.component
Project structure (minified to match errormessage's scope)
src
|
--config
| |
| --karma.conf.js
| --karma-shim.ts
| --protractor.conf.js
| --rollup.config.js
|
--pages
| |
| --events
| |
| --events.component.ts
|
--services
|
--APICaller.service.ts
Karma.conf.js:
'use strict';
const path = require('path');
const ts = require('rollup-plugin-typescript');
const buble = require('rollup-plugin-buble');
const nodeResolve = require('rollup-plugin-node-resolve');
const angular = require('rollup-plugin-angular');
const commonjs = require('rollup-plugin-commonjs');
const alias = require('rollup-plugin-alias');
module.exports = function karmaConfig(config) {
var configuration = {
// base path that will be used to resolve all patterns (e.g. files, exclude)
basePath: '../',
frameworks: ['jasmine'],
plugins: [
require('karma-jasmine'),
require('karma-phantomjs-launcher'),
require('karma-rollup-plugin')
],
reporters: [
// // Reference: https://github.com/mlex/karma-spec-reporter
// // Set reporter to print detailed results to console
// 'spec',
// // Reference: https://github.com/karma-runner/karma-coverage
// // Output code coverage files
// 'coverage'
'progress'
],
// list of files / patterns to load in the browser we are building
// the config environment in ./karma-shim.js
files: [
'config/karma-shim.ts'
],
preprocessors: {
'config/karma-shim.ts': ['rollup']
},
rollupPreprocessor: {
context: 'this',
plugins: [
angular({
exclude: 'node_modules/**'
}),
ts({
typescript: require('../node_modules/typescript')
}),
alias({
'#angular/core/testing': path.resolve(__dirname, '../node_modules/#angular/core/testing/index.js'),
'#angular/platform-browser-dynamic/testing': path.resolve(__dirname, '../node_modules/#angular/platform-browser-dynamic/testing/index.js'),
'#angular/compiler/testing': path.resolve(__dirname, '../node_modules/#angular/compiler/testing/index.js'),
'#angular/platform-browser/testing': path.resolve(__dirname, '../node_modules/#angular/platform-browser/testing/index.js')
}),
commonjs(),
nodeResolve({ jsnext: true, main: true, browser: true }),
buble()
]
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
// Continuous Integration mode if true, Karma captures browsers, runs the tests and exits
singleRun: true
};
// if(process.env.GITLAB_CI){
// //configuration.browsers = ['Chrome_travis_ci'];
// }
config.set(configuration);
};
Karma-shim.ts
declare var __karma__: any;
__karma__.loaded = () => { };
import 'core-js/client/shim';
import 'reflect-metadata';
import 'zone.js/dist/zone';
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/proxy';
import 'zone.js/dist/jasmine-patch';
import 'rxjs/Rx';
import { TestBed } from '#angular/core/testing';
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '#angular/platform-browser-dynamic/testing';
TestBed.initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
import '../src/pages/home/home.spec';
import '../src/pages/events/events.spec';
import '../src/pages/event-detail/event-detail.spec';
__karma__.start();
rollup.config.js
const rollupConfig = require('../node_modules/#ionic/app-scripts/config/rollup.config');
const replace = require('rollup-plugin-replace');
console.log('Editing default ionic configuration');
const nodeEnv = JSON.stringify(process.env.NODE_ENV) || 'development';
const apiUrl = JSON.stringify(process.env.API_URL) || '';
const platform = JSON.stringify(process.env.PLATFORM) || 'android';
rollupConfig.plugins.push(replace({
'process.env.NODE_ENV': nodeEnv,
'process.env.API_URL': apiUrl,
'process.env.PLATFORM': platform
}));
module.exports = rollupConfig;
I figured that Bamboo is case-sensitive. And since my APICaller doesn't follow the angular's kebab-case, Bamboo couldn't find the path.
Class was APICaller.service.ts and import was {..} from 'apicaller.service. Change to {..} from 'APICaller.service made it work