Jest does not find paths in CI
I want to test my typescript library.
It has two parts: core and client. client
instance core
to use its functions.
import { Core } from "@lib/core";
class Client {
constructor() {
new Core();
}
}
To make these two parts independent, I use lerna
as it they were separated npm packages: @lib/core
and @lib/client
.
Everything runs ok in local environment, but in gitlab CI this error is thrown before the client tests start:
Cannot find module '@lib/core' from 'src/lib/client.spec.ts'
3 |
> 4 | jest.mock('@lib/core');
| ^
lerna.json
{
"packages": ["packages/core", "packages/client"],
"version": "independent",
"npmClient": "npm"
}
.gitlab-ci.yml
image: node:14
cache:
paths:
- node_modules
- .npm
- dist
---
unit:
stage: test
script:
- npx jest --clear-cache
- npm run test
I have tried adding path configuration in tsconfig.json, to see if jest did recognize them this way. Result: runs ok in local but fails in CI
tsconfig.json
{
"compilerOptions": {
"paths": {
"@lib/core": ["dist/core"],
"@lib/client": ["dist/client"]
}
}
}
jest.config.js
const { pathsToModuleNameMapper } = require("ts-jest/utils");
const { compilerOptions } = require("./tsconfig");
module.exports = {
preset: "jest-preset-angular",
roots: ["<rootDir>/src/"],
testMatch: ["**/+(*.)+(spec).+(ts)"],
setupFilesAfterEnv: ["<rootDir>/src/test-setup.ts"],
collectCoverage: true,
coverageReporters: ["html"],
coverageDirectory: "coverage",
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths || {}, {
prefix: "<rootDir>/",
}),
cache: false,
};
See also questions close to this topic
-
Errro add component in Angular 11
When I try to add a component to app, appears this error but I don't know what is happen
My code
Error: src/app/product/product.component.ts:7:14 - error NG6002: Appears in the NgModule.imports of AppModule, but could not ble.imports of AppModule, but could not be resolved to an NgModule class. Is it missing an @NgModule annotation?
product.component.ts in app/product
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-product', templateUrl: './product.component.html', styleUrls: ['./product.component.scss'] }) export class ProductComponent implements OnInit { constructor() { } ngOnInit(): void { } }
app.module.ts
import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ProductComponent } from './product/product.component'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ProductComponent ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
app.component.html
<app-product></app-product>
-
How can I pass an optional argument to an overloaded function in Typescript?
I have an overloaded function that I'm calling with an optional parameter. I'm having trouble figuring out how to get Typescript to find the errors correctly in this.
function inner<T>(innerArg: T) { function foo(): T; function foo(a: boolean): T & { a: boolean }; // function foo(a?: boolean): T | T & { a: boolean }; function foo(a?: boolean) { return a ? { ...innerArg, a } : innerArg; } return foo; } function wrapper<T>(outerArg: T, a?: boolean) { return inner(outerArg)(a); // Argument of type 'boolean | undefined' is not assignable to parameter of type 'boolean'. } const arg = { b: 1 } console.log(wrapper(arg).b); // 1 console.log(wrapper(arg, true).a); // true console.log(wrapper(arg, true).b); // 1 console.log(wrapper(arg).a); // should generate compilation error
If I uncomment that fourth line, adding an overload signature with an optional, the error in the wrapper goes away. However, then I get an error from the third to last line,
console.log(wrapper(arg, true).a);
which should be valid and which prints 'true'.
Is there a way of typing
inner
such that Typescript will correctly identify correct and incorrect usages ofinner
andwrapper
? -
Angular KeyValue Pipe not working on string/number enum, showing duplicates
How come this Angular keyvalue pipe is not working on enum below?
export enum test{ "Honda Accord" = 2 }; <div *ngFor="let testItem of test | keyvalue"> {{test.key}}
Its showing this in my Angular dropdown, both Key and Value twice. I only want to see Honda Accord text.
When I make 2 with a string quote, it will work. I want it working both ways.
export enum test { "Honda Accord" = "2" };
-
How to install a mock library into a unit test in Angular? I want to install sinon-chrome into a spectator test
I am working on a Google Chrome extension which is written in angular and I need to write unit tests for components that make use of the Chrome API. I found a library that I believe will do the job.
https://www.npmjs.com/package/sinon-chrome
However, I do not have enough experience with Angular to know how exactly to put the library into use. The usage section says that I need to require the value in a constant, but I have no idea how or where that would go. Does that go in the unit test? Does that go in the
karma
file? What is theglobal.chrome
that is found in the examples.The code for my unit test. It otherwise runs fine except for this chrome mock issue.
const angularFireAuthMock = { // eslint-disable-next-line @typescript-eslint/no-empty-function onAuthStateChanged: () => {}, }; describe('AppComponent', () => { let spectator: Spectator<AppComponent>; const createComponent = createComponentFactory({ component: AppComponent, mocks: [FirestoreService], providers: [{ provide: AngularFireAuth, useValue: angularFireAuthMock, }] }); beforeEach(() => { spectator = createComponent(); }); it('should create the app', () => { expect(spectator.component).toBeDefined(); }); });
AppComponent
is where the ChromeThanks for your help.
-
How to write test for component containing ThemeProvider as a wrapper to its child components in react native
Following is the basic functional component that is wrapped around by ThemeProvider provided by react-native-elements
const Page = ({route, navigation}: Props) => { // some states and functions return( <View> <ThemeProvider theme={ //some code here }> <View> //some component here </View> </ThemeProvider> </View> ) }
I am trying to write a snapshot tests for Page component as below :
const tree = renderer.create(<Page/>); expect(tree.toJSON()).toMatchSnapshot();
But i am getting following error :
console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:10695 The above error occurred in the component: in Page
I have tried testing component by wrapping Page itself as below :
const tree = renderer.create( <ThemeProvider <Page/> </ThemeProvider>); expect(tree.toJSON()).toMatchSnapshot();
But this does not solved the issue. I am not able to find a way to mock a component that itself contains ThemeProvider. If i remove ThemeProvider from the component test passes like charm.
Any helps would be appreciated. Thanks.
-
How to Unit test Spring-Boot Application main() method to get Jacoco test coverage
How to Unit test Spring-Boot Application main() method with SpringApplication.run() . I am wondering if it is possible to get Jacoco test coverage on this class. (Otherwise I will exclude it)
This question is similar, but not the same, as this question: Spring Boot, test main application class
I am using
mockito-core
3.8 andmockito-inline
.This test code works for me but Jacoco does not pick it up as test coverage:
@SpringBootTest @ActiveProfiles("test") public class AutowireTest { private static final String ARG = ""; private static final String[] ARGS = new String[]{ARG}; @Autowired ConfigurableApplicationContext context; @Test public void main() { try (MockedStatic<Application> appStatic = Mockito.mockStatic(Application.class); MockedStatic<SpringApplication> springStatic = Mockito.mockStatic( SpringApplication.class)) { appStatic.when(() -> Application.main(ARGS)) .thenCallRealMethod(); springStatic.when(() -> SpringApplication.run(Application.class, ARGS)) .thenReturn(context); // when Application.main(ARGS); //then appStatic.verify(times(1), () -> Application.main(ARGS)); springStatic.verify(times(1), () -> SpringApplication.run(Application.class, ARGS)); } } }
Is Jacoco not able to show coverage on static methods?
-
How can make an Automatic tests for Teradata
I am using SQL Teradata. My team and I are looking for a tool to automate testing. I'm not talking about a data quality test tool that I can do with a tool like Talend Data Quality.
I'm looking for a tool for the automation of tests for SQL Teradata.
Does someone have an idea?
thanks in advance,
Best regards, Slim
-
test cafe : removeRequestHook
So I use t.addRequestHooks to add a few requestMock
I have the impression that after the end on my test, the hook are still working.
Is there a way to remove all the requestMock in one line? or should I specify all the t.removeRequestHooks one by one?
-
How to test custom gradle plugin both with JUnit and manually in same sample project
My goal is to have this project setup:
example-gradle-plugin ├── build.gradle └── src ├── main │ ├── java │ │ └── com .... └── test ├── java │ └── example │ └── integrationtest │ │ # GradleRunner.create().withProjectDir(testProjectPath.toFile()).withPluginClasspath() │ └── SimpleProjectRegressionTest.java // └── resources └── simple │ # plugins { id "example-gradle-plugin" } ├── build.gradle │ # // includeBuild ../../../../example-gradle-plugin └── settings.gradle
So the folder src/test/resources/simple is both used from a JUnit test, but as well can be used to run gradle commands from the command line using the composite build approach.
So this should work
cd src/test/resources/simple gradle build
And this unit test should also work:
@Test public void testBuildSample() { final ClassLoader classLoader = ProjectSetupHelper.class.getClassLoader(); final Path sampleSourceRootPath = Paths.get(classLoader.getResource("simple").toURI()); final BuildResult result = GradleRunner.create() .withProjectDir(sampleSourceRootPath.toFile()) .withArguments("build") .withPluginClasspath() .build(); }
However, there is a caveat when running JUnit, the custom-plugin-sources are referred to in 2 different ways at the same time:
GradleRunner.create().withProjectDir(testProjectPath.toFile()).withPluginClasspath()
means to add project custom plugin files to the classpath for running the build during the unit test- In
src/test/resources/simple/settings.gradle
, theincludeBuild ...
command also refers to the custom plugin.
Is there an easier or cleaner way to achieve the above: Having a sample project with composite build that can be used from the commandline to verify local changes to the plugin, and using that sample project also in a unit test of the plugin?
Currently in the unit test I copy the sample folder to a temporary folder without settings.gradle to avoid such complications.
-
More than one test fails due to import after jest is torn down - Supertest Typescript and Express API
I am running into an issue where I am running multiple tests using
supertest
andjest
. When there is only one test running then it works just fine but the second one throws the following error:ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
I tested this with two very simple tests:
describe("Default API", () => { describe("Default:", () => { it("should create a user in the DB", (done) => { request(app).get("/").expect(200, done); }); it("should create a user in the DB", (done) => { request(app).get("/").expect(200, done); }); }); });
They are the same but the second one throws the error. If I run only the first one there is no issue. This must be a setup issue Does anyone have advice. In my index.ts where I have the main express code I export app as follows:
export default app;
This is at the bottom of the index.ts file.
-
TypeError: Cannot read property 'getContext' of null
I have created a game using canvas API and now I am testing using Jest. But when running a test for a simple function it throws me this error. my script tag is at the end of the HTML and I also added this event listener to wait for the DOM document.addEventListener("DOMContentLoaded", init,false);
jest
PASS tests/sum.test.js FAIL tests/mod.test.js ● Test suite failed to run
TypeError: Cannot read property 'getContext' of null 20 | const empty = 0; 21 | const nextPieceCanvas = document.querySelector("canvas#nextPiece") as HTMLCanvasElement; > 22 | const NPctx = nextPieceCanvas.getContext("2d")! as CanvasRenderingContext2D; | ^ 23 | 24 | //Gameboard Canvas 25 | const canvas = document.querySelector("canvas#tetris") as HTMLCanvasElement; at Object.<anonymous> (src/ts/app.ts:22:31) at Object.<anonymous> (tests/mod.test.js:2:1)
Test Suites: 1 failed, 1 passed, 2 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.424 s Ran all test suites. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! tetris_ts@1.0.0 test:
jest
npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the tetris_ts@1.0.0 test script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.npm ERR! A complete log of this run can be found in: npm ERR! /home/alex/.npm/_logs/2021-02-26T22_46_02_771Z-debug.log
enter code here
-
nestjs unit test createTestingModule Dependency Injection
I hope you can help me out. I am using Nx with latest angular/nestjs (date: February, 26)
... "@nestjs/common": "^7.0.0", "@nestjs/config": "^0.6.3", "@nestjs/core": "^7.0.0", "@nestjs/platform-express": "^7.0.0", "@nestjs/platform-socket.io": "^7.6.7", "@nestjs/websockets": "^7.6.7", "jest": "26.2.2", "@nrwl/jest": "11.4.0", ...
I cannot get my unit test running using NestJS with Jest I want to test following service:
@Injectable() export class CoreApiService { logger = new Logger('CoreApiService'); apiEndpoint; constructor(private httpService: HttpService, configService: ConfigService) { this.apiEndpoint = configService.get('API_SERVICE_ENDPOINT'); } }
and I get following error:
TypeError: Cannot read property 'get' of undefined
so it seems that the ConfigService (and also httpService) is always undefined.
when logging httpService and ConfigService, it will always be undefined. Even when I try to instantiate new Instances like
new CoreApiService(new HttpService(), new ConfigService())
I've even tried things likenew CoreApiService({} as any, {get: (...params} => {return 'foo'})
in the test itselfit will always be the same error mentioned above.
The test file:
import { Test, TestingModule } from '@nestjs/testing'; import { CoreApiService } from './core-api.service'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { HttpModule } from '@nestjs/common'; class ConfigServiceMock { get(key: string): string { switch (key) { case 'API_SERVICE_ENDPOINT': return ''; } } } describe('CoreApiService', () => { let module: TestingModule; let service: CoreApiService; beforeEach(async () => { module = await Test.createTestingModule({ imports: [HttpModule, ConfigModule], providers: [ CoreApiService, { provide: ConfigService, useClass: ConfigServiceMock }, ], }).compile(); service = module.get<CoreApiService>(CoreApiService); }); it('should be defined', () => { expect(service).toBeDefined(); }); });
I've even tried:
.overrideProvider(ConfigService).useClass(ConfigServiceMock)
Thank you in advance!
-
Deployment Strategy using Lerna
https://github.com/AnomalyInnovations/serverless-lerna-yarn-starter
From the link above,
Deployment We want to ensure that only the services that have been updated get deployed. This means that, if a change is made to:
services
Only the service that has been changed should be deployed. For ex, if you change any code in service1, then service2 should not be deployed.
packages
If a package is changed, then only the service that depends on this package should be deployed. For ex, if sample-package is changed, then service1 should be deployed.
libs
If any of the libs are changed, then all services will get deployed.
Deployment Algorithm To implement the above, use the following algorithm in your CI:
Run lerna ls --since ${prevCommitSHA} -all
to list all packages that have changed since the last successful deployment. If this list includes one of the services, then deploy it.Run git diff --name-only ${prevCommitSHA} ${currentCommitSHA}
to get a list of all the updated files. If they don't belong to any of your Lerna packages (lerna ls -all), deploy all the services.Otherwise, skip the deployment.
Problem:
lerna ls --since ${prevCommitSHA} -all
This command lists all the packages for me since I am not publishing the package anywhere but will only be running lerna run deploy command which will run sls deploy in services/packages.
- How to get rid of Lerna Warnings on "yarn" command
-
Causing an error by creating a monorepo with circular dependencies
I'm relatively new to monrepo's/yarn workspaces/lerna. I was working on a React / TypeScript monorepo where I cleaned up circular dependencies. I just think they shouldn't exist in a clean code architecture. I know that they make life easier when you want to refactor parts of an app, study the app's architecture or just want to reference one of the repo's in another project.
But can someone provide a good example of where a circular dependency is actually causing an error in a TypeScript/React project? Probably related to importing Types in a circular way, or somewhere else?
Many thanks in advance!
Achim