Issue Good day developers . Im trying to test the show hide behaviour of a <li/> tag according to a specific variable. For that this <li/> tag has an *ngIf bound: <ul class="item" js-selector="tab-list"> <li class="item" js-selector="tab" *ngIf="isTabEnabled" … >
Continue readingTag: jestjs
Angular 9 new unit test error: "unsafe value used in a resource URL context"
Issue Since upgrading my Angular application from version 8 to version 9 I’ve got a new error appearing when I run my Jest unit test: unsafe value used in a resource URL context (see http://g.co/ng/security#xss) The component I am testing
Continue readingUsing environment variables in Node and Jest
Issue I have a NodeJS app. For a long time I’ve been using Mocha to run tests. I simply had a package.json like "dev": "node index –env=dev", "start": "node index", "test": "mocha ‘./test/**/*.spec’ –env=dev" Now I am switching to Jest
Continue readingJest instantiating empty objects instead of class instances
Issue I’m using ts-jest to test a JS/TS SDK/module. I’m running into a strange issue where a Jest test will run (no compile/import failures) but fail to correctly instantiate an object from the appropriate class. test("Should build unit", () =>
Continue readingHow to mock navigator.clipboard.writeText() in Jest?
Issue I have tried the following 4 options after looking at Jest issues and SO answers, but I am either getting TypeScript errors or runtime errors. I would really like to get option 1 (spyOn) working. // —— option 1
Continue readingJest: SVG require causes "SyntaxError: Unexpected token <"
Issue Not sure where to look for this error. Using Typescript with React, and Jest and Enzyme for unit testing. Package.json sample: “scripts”: { “start”: “node server.js”, “bundle”: “cross-env NODE_ENV=production webpack -p”, “test”: “jest” }, “jest”: { “transform”: { “^.+\\.tsx?$”:
Continue readingWhat is the simplest way to mock a fetch call that is only meant to run in the browser with jest?
Issue If I’m testing a function that makes a fetch call, and all the fetch calls I have in the project are only meant to run in the browser. Do I still need to have some package installed on node
Continue readingHow test request http with parameters with jest – angular
Issue I’m testing an angular service with Jest. I can to mock my httpClient, but I have a problem it is that I cannot test a url with a parameter (ex: “http://localhost:8080/api/feature/num?id=25663“). This my test code : describe(‘MyService’, () =>
Continue readingJest test functions on select statements in React JS
Issue I am new to testing in jest and I was wondering if I could receive some clarity on a matter I am having difficulty understanding. const getSelectField = () => <SelectField name={name} id={id} aria-label="test" value={value} options={options} />; describe(‘Select Field’,
Continue readingHow to mock useHistory hook in jest?
Issue I am using UseHistory hook in react router v5.1.2 with typescript? When running unit test, I have got issue. TypeError: Cannot read property ‘history’ of undefined. import { mount } from ‘enzyme’; import React from ‘react’; import {Action} from
Continue readingCannot find module 'babel-preset-env' from PATH Did you mean "@babel/env"?
Issue Jest cli suddently has stopped working, all test fails with: Cannot find module ‘babel-preset-env’ from ‘/PATH’ – Did you mean "@babel/env"? I’m sure it is some kind of incompatibility between a module which uses babel 6 and my project
Continue readingHow to mock AWS Cognito CognitoIdentityServiceProvider with Jest?
Issue I’m trying to write unit test where I need to mock response of method from cognito service – CognitoIdentityServiceProvider I have the following working code calling the adminInitiateAuth operation import * from AWS from ‘aws-sdk’ const cognito = new
Continue readingreactjs empty data when mocking axios.get with jestjs mock
Issue I am developing an application in react and for the first time I decided to implement tests. I started with the simpler components, which I still had trouble with, but now I would like to test more complex components,
Continue readingJest test fails with Unexpected token, expected ";"
Issue I have a Node project using Typescript and Jest. Currently I have this project structure With this tsconfig.json file “compilerOptions”: { “target”: “ES2017”, “module”: “commonjs”, “allowJs”: true, “outDir”: “dist”, “rootDir”: “src”, “strict”: true, “moduleResolution”: “node”, “esModuleInterop”: true } this
Continue readingJest test assertion, expect a nested object
Issue When I do the below expect in jest with native test expect(mockOnChange).toHaveBeenCalledWith({ order_type: expect.arrayContaining([‘1’]), number: ”, ouser_ids: expect.arrayContaining([‘user_id1’]), payment_type: expect.arrayContaining([‘2’]), start_date: old_Date, end_date: current_date, state: ‘all’, }); I’m getting the following error Object { "end_date": "2022/06/07", "number": "", –
Continue readingTest unable to run test cases exits with TypeError: Jest: a transform must export a `process` function
Issue { //tsconfig.base.json "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "downlevelIteration": true, "experimentalDecorators": true, "module": "esnext", "moduleResolution": "node", "importHelpers": true, "target": "es2015", "typeRoots": ["node_modules/@types"], "lib": ["es2018", "dom"] }, "angularCompilerOptions": { "fullTemplateTypeCheck": true, "strictInjectionParameters": true }
Continue readingHow can I mock an ES6 module import using Jest?
Issue I want to test that one of my ES6 modules calls another ES6 module in a particular way. With Jasmine this is super easy — The application code: // myModule.js import dependency from ‘./dependency’; export default (x) => {
Continue readingHow to prevent redundant code in my jest e2e testing?
Issue I am just learning to build e2e tests with Jest and Supertest. Test background Some APIs are protected by Api Keys so I need to create them on the test before running these APIs. The problem is that I
Continue readingSonarQube coverage deviates of Jest coverage
Issue I’m having hard time to understand why SonarQube has different coverage results compared to Jest coverage. SQ coverage results Jest coverage My question is, why does the coverage deviate with a noticeable amount and how can you prevent this
Continue readingJest: I want to put test code under 'Project/test/' directory, but configuration error occured
Issue I want to put my test code under ‘Project/test/’ directory, not ‘Project/src/moduleName/’. So I changed jest configuration at package.json. rootDir "src" => "test" moduleNameMapper "^src/(.)$": "<rootDir>/$1" => "^src/(.)$": "src/$1" "jest": { "rootDir": "test", "moduleNameMapper": { "^src/(.*)$": "src/$1" }, "moduleFileExtensions":
Continue readingAxios mock: Received number of calls: 0
Issue I am trying to do a simple mock for my get All method.I’m getting this error: Expected number of calls: 1 Received number of calls: 0 following is my mock configurations. jest.mock("axios", () => { return { create: jest.fn(()
Continue readingHow to mock NODE_ENV in unit test using Jest
Issue I want to set NODE_ENV in one of the unit test but it’s always set to test so my tests fails. loggingService.ts … const getTransport = () => { if (process.env.NODE_ENV !== "production") { let console = new transports.Console({
Continue readingexpo app with testing react-native-testing-library and jest-native "has no exported member 'toHaveProp"
Issue I’m trying to use jest-native as extra matchers and i’m having an installation problem i think … I am on a react-native ts app with expo and here are my versions: expo:"~39.0.0" @testing-library/react-native version:"^7.1.0" jest-preset: ‘jest-expo’, react-native version:" 63.4
Continue readingTesting Mocked Fetch Api in Jest returns undefined
Issue I have a generic FetchService in React/TS like this: /* Generic Fetch Service */ const FetchService = { call: async (url:string) => { try { return await fetch(url) .then((res) => res.json()) .then((data) => { data.response}); } catch (e) {
Continue readingHow to get a Jest custom matcher working in typescript?
Issue I regularly have unit tests where I need to compare two moment objects. I’d us moment’s built-in function moment.isSame(moment) to compare them. However, this means my assertion will look like this: expect(moment1.isSame(moment2)).toBeTrue(); I didn’t quite like this, especially because
Continue readingJest called chain of imported dependencies of module
Issue When I created instance of Atom jest show error with piece of code that i haven’t invoced. I assume it connects with modules that have imported in class that I try to create. I begin to mock modules showed
Continue readingtsconfig problems with test and compiling
Issue This is my tsconfig.json { "compilerOptions": { "noImplicitAny": true, "declaration": false, "strict": true, "strictNullChecks": false, "target": "ES2019", "module": "commonjs", "resolveJsonModule": true, "allowJs": true, "checkJs": false, "outDir": "dist", "esModuleInterop": true, "inlineSourceMap": true, "rootDir": "./", "baseUrl": "./", "typeRoots": [ "./node_modules/@types" ],
Continue readingJest global teardown runs before tests finish?
Issue I’m trying to make sure my app gets properly destroyed after all my Jest tests have run, but I’m running into some very strange behaviour trying to use Jest’s global teardown config value. Here’s the situation: my app creates
Continue readingJest Spy not being called
Issue I am trying to run a test using the winston logger package. I want to spy on the createlogger function and assert that it is being called with the correct argument. Logger.test.ts import { describe, expect, it, jest, beforeEach,
Continue readingHow to stop Jest from hanging when testing WebSockets?
Issue I created an app in node.js which gives me a WebSocket interface using the ‘ws’ package from NPM on the server. Now I want to test this interface with Jest. The test runs successful but Jest does not exit
Continue readingJest/Rxjs – timeout when calling for subscription from a getter
Issue I have a service that updates an Rxjs Subject whenever a method in the service is called: @Injectable() export class AppAlertService implements IAppAlertService { private readonly _alertBehaviourSubject: Subject<IAlertConfiguration> = new Subject<IAlertConfiguration>(); public get alertConfiguration(): Observable<IAlertConfiguration> { return this._alertBehaviourSubject.asObservable(); }
Continue readingHow to resolve console error unhandled promise rejection when unit testing?
Issue I have a method that handles error codes: handleSignatureAppErrorCodes(code) { if (code === 10) { return this.handleError({ message: ‘Configuration error, contact administrator’, }); } else if (code === 11) { return this.handleError({ message: ‘ Certificate not available’ }); }
Continue readingUsing Jest with Angular 13 + Clarity
Issue i am currently attempting to upgrade an existing Angular app which uses VMware Clarity. I already managed to upgrade from 8.x to 10.x following the Angular update guidelines. However beyond that the jest configuration breaks, as the newer Clarity
Continue readingHow to test a http request function in a service with Angular and Jest
Issue I created a simple service returning a json object. getCountries() { return this.httpService.get(‘../../assets/countries.json’); } The test describe(‘TestServiceService’, () => { let service: TestServiceService; let httpController: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule] }); httpController = TestBed.inject(HttpTestingController); service = TestBed.inject(TestServiceService);
Continue readingProperty 'toHaveStyle' does not exist on type 'JestMatchers<Element>'
Issue I have a Color Directive which set background-color to card. I dont understand how to testing it by Jest @Input(‘appColor’) public color: string; constructor( private element: ElementRef, private render: Renderer2, ) { } public ngAfterViewChecked(): void { this.setCategoryColor(); }
Continue readingAngular 8 and jest – File not found: jest-preset-angular/InlineHtmlStripStylesTransformer.js
Issue I just created angular application using the cli (v8 – last version from today). nothing special I done so far. (ng new ng-app). I use jest-schematic to add jest to my angular project. cd ng-app ng add @briebug/jest-schematic The
Continue readingWatch and rerun Jest JS tests
Issue The Jest documentation suggests using npm test to execute tests. Is there a way of watching your source and tests to rerun Jest tests automatically when relevant files have been changed? Solution Thanks to Erin Stanfill for pointing out,
Continue readingError while running Jest tests in @nrwl/nx workspace
Issue I recently started to convert my Angular apps and libs into an @nrwl/nx workspace. The apps are running fine, however when it comes to my Jest tests I get some strange errors. The workspace is a standard NX workspace
Continue readingAngular/Jest – Test that the subject has thrown error after setter is called
Issue I have a class that is responsible for setting the theme for my application. I’m trying to test that it throws an error if you give it a theme that it does not recognise. The code is shown below
Continue readinghow to create instance of class with jest
Issue I am a beginner in writing tests and in jest also. I want to test that this function to be called and return the success promise. I write a unit test for function using jest. The function gets like
Continue readingTesting with 'toHaveStyle' passes when expecting fail
Issue I’m learning about testing and react. I’m having a little trouble understanding why a test is passing when it should not: From App.js <button style={{backgroundColor: ‘gray’}}> Gray button </button> From App.test.js expect(colorButton).toHaveStyle( {backgroundColor: ‘gray’ }); // passes ok expect(colorButton).toHaveStyle(
Continue readingHow to test if a function set something to localStorage with Jest?
Issue I want to test a function that writes something to localStorage using Jest. The function in question is the following: const items: = [ { name: ‘Item One’, }, ]; export const init = () => { if (!localStorage.getItem(‘items’))
Continue readingHow to mock a specific method of a class whilst keeping the implementation of all other methods with jest when the class instance isn't accessible?
Issue Based on this question (How to mock instance methods of a class mocked with jest.mock?), how can a specific method be mocked whilst keeping the implementation of all other methods? There’s a similar question (Jest: How to mock one
Continue readingHow to mock AxiosInstance?
Issue I have axios with following HttpClient class export default class HttpClient { constructor(baseUrl: string) { const axiosInstance = axios.create({ validateStatus(status: number) { return status === 200 || status === 201; }, }); axiosInstance.interceptors.request.use((config) => { if (AuthUtil.getAuthHeader()) config.headers =
Continue readingJest – testing httpClient rejected promise
Issue I have an Nest.js application and I’m trying to test a method that has a simple httpClient request, but I can’t find a way to test the catch block from my code. async getUser(): Promise<any> { try { return
Continue readingProblem in the tsconfig.json file when trying to use Jest with Typescript
Issue The error message I am getting is: File ‘d:/Project/server/jest.config.ts’ is not under ‘rootDir’ ‘d:/Project/server/src’. ‘rootDir’ is expected to contain all source files. The file is in the program because: Matched by include pattern ‘**/*’ in ‘d:/Project/server/tsconfig.json’ My tsconfig.json file
Continue readingMock function not called and not resolving or returning mocked value in React jest API testing
Issue I am using jest to test the axios API calls. Mocking the API is not resolving or returning a value and mock function is not called. Here is my code for API call and testing. // import axios from
Continue readingHow to install typescript + jest with create-react-app?
Issue I want to install typescript and jest in a create-react-app-based app. I feel that since this is such a common installation choice there must be at least one "everything just works" set of configuration steps to follow. I initially
Continue readingHow to mock a constructor instantiated class instance using jest?
Issue Given a class Person that instantiates & uses another class Logger, how can the Logger‘s method be verified to be called when Person is instantiated in the example below? // Logger.ts export default class Logger { constructor() {} log(m:
Continue readingTesting using setTimeout(fn, 0). What this snippet of testing code does?
Issue This is a snippet from a unit test file that use jest. The parse function returns a Promise after the parse is completed… But I cannot understand the use of that boolean flag (completedAsyncDummyTask). it("parse is a promise that
Continue readingJest: function that should throw does not pass and test will fail
Issue I want to test a function A that calls multiple other functions inside it which can throw errors. Here is an abstraction of my code: // file A.ts const A = (args: any[]): boolean => { (() => {
Continue readingaws cdk 2.0 init app fails to build with prettier issues, which is from jest-snapshot
Issue node: v16.7.0 cdk: 2.0.0 (build 4b6ce31) package.json: "devDependencies": { "@types/jest": "^26.0.10", "@types/node": "10.17.27", "aws-cdk": "2.0.0", "jest": "^26.4.2", "ts-jest": "^26.2.0", "ts-node": "^9.0.0", "typescript": "^3.9.7" }, "dependencies": { "aws-cdk-lib": "2.0.0", "constructs": "^10.0.0", "source-map-support": "^0.5.16" } npm run build/watch stack trace: node_modules/@types/prettier/index.d.ts:41:54
Continue readingJest beforeAll vs beforeEach unexpected behaviour
Issue I have a quite simple test, basically I’m trying to mock i18next’s t function: import { t } from ‘i18next’; import { changeDocumentTitle } from ‘./utils’; jest.mock(‘i18next’); const tMock = (key: string): string => key; beforeAll(() => { (t
Continue readingHow to mock x-date-pickers from mui in jest?
Issue I added a DateTimePicker to my app which seems to work, however, I’m unable to mock the picker in my Jest tests. I keep getting the following error: Test suite failed to run TypeError: (0 , _material.generateUtilityClasses) is not
Continue readingJest won´t complete my async function for my api call function
Issue I´m working on a small app that uses an API. I want to make a test to see that the function works as intended. The function works, but in the test, the function will not complete and therefore fail.
Continue readingJest – mock a named class-export in typescript
Issue I have a node module which exports a few classes, one of which is Client, which I use to create a client (having a few APIs as methods). I’m trying to test my module which uses this node module
Continue readingJest – mock a named class-export in typescript
Issue I have a node module which exports a few classes, one of which is Client, which I use to create a client (having a few APIs as methods). I’m trying to test my module which uses this node module
Continue readingTesting if an event has been triggered in NestJS
Issue In the project we are building, there is a standard sequence in the workflow. Controller receives a request Then fires an event through @nestjs/event-emitter Event listener listens to it and executes some code depending on the event How can
Continue readingReact-scripts test: no traceback on exception
Issue I remake browser version of TacticToy game with React, and during unit-tests writing I’ve got a problem: there is no full traceback of a custom exception, only test function is highlighted: In the package.json file’s scripts section I have
Continue readingMock 'S3' feature of 'aws-sdk' (nodeJS and Jest)
Issue I need to test a file in charge of retrieving data from S3 through the ‘aws-sdk’ (nodeJs + Jest). The file is: const AWS = require(‘aws-sdk’); let S3 = null; const getS3 = async () => { if (S3
Continue readingNode v13 / Jest / ES6 — native support for modules without babel or esm
Issue Is it possible to test ES6 Modules with Jest without esm or babel? Since node v13 supports es6 natively have tried: //package.json { … “type”: “module” … } //__tests__/a.js import Foo from ‘../src/Foo.js’; $ npx jest Jest encountered an
Continue readingHow to disable Morgan (request logger) during unit test?
Issue I use Morgan (default express generator request logger), and I’m trying to disable it during unit testing. Currently I’m using the default configuration, which loads Morgan in app.js const logger = require(‘morgan’); … const app = express(); … app.use(logger(‘dev’));
Continue readingHow do I test a single file using Jest?
Issue I am able to test multiple files using Jest, but I cannot figure out how to test a single file. I have: Run npm install jest-cli –save-dev Updated package.json: `{ … "scripts": { "test": "jest" } … } Written
Continue readingHow to stop a commit if test coverage is below a certain percentage?
Issue I’m using Jest to test a NestJS application and I’m trying to create a git hook with husky that will not allow a commit if tests coverage are under 95%, I haven’t tried anything yet cause I really don’t
Continue readingJest: to check if a function is called by a specific instance of class in JavaScript/Typescript
Issue I am testing some express middlewares with jest. it("should throw 400 error if request.body.id is null", () => { const req = { body: { id: null } } as any; const res = {} as any; const next
Continue readingTypescript paths not resolving when running jest?
Issue Attempting to convert this project over to jest using these instructions. I have everything working except for the files that use the paths configuration: “paths”: { “@fs/*”: [“./src/*”], “@test/*”: [“./test/*”] } It looks as if when the tests are
Continue readingQuery a simple button with jest and
Issue I’m trying to test my component, so here it’s : import React from ‘react’; import { useNavigate } from ‘react-router-dom’; import ‘../styles/mainPageStyles.css’; const MainPage = (): React.ReactElement => { const navigate = useNavigate(); const handleBeginQuiz = () => {
Continue readingHow to test NestJs response interceptor
Issue I tried to follow this thread but it I keep getting an error. transform-response.interceptor.ts: import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from ‘@nestjs/common’; import { Observable } from ‘rxjs’; import { map } from ‘rxjs/operators’; import { ApiResponseInterface }
Continue readingTest coverage: import statements not covered
Issue I’m writing tests with Jest for a Nest application in typescript. The problem is, I have uncovered import statements saying else path not taken" and "branch not covered". The uncovered imports vary across classes. Sometimes it is underlined seemingly
Continue readingHow to spyOn a function that is not part of the class under test with Jest and Typescript
Issue I’m trying to spy on a function that come from uuidv4 package but I didn’t figure out how to do that. This is my User Class: import { uuid } from ‘uuidv4’; import { IUser } from ‘../interfaces/IUser’; export
Continue readingMocking a default export function with Jest: TypeError: (0 , _sampleFunction).default is not a function
Issue I have the following files: sampleFunction.ts: export default (x: number) => x * 2; testFile: import sampleFunction from ‘./sampleFunction’; export default () => { const n = sampleFunction(12); return n – 4; }; testFile.test.ts: import testFile from ‘./testFile’; const
Continue readingTest invalid function arguments with TypeScript and JestJS
Issue I’ve beend creating a node application with typescript and I’m using jest to write unit tests. My issue: I can’t really write unit tests simulating invalid function argument types, because typescript won’t compile. I mean it’s nice that typescript
Continue readingReact testing library: Test styles (specifically background image)
Issue I’m building a React app with TypeScript. I do my component tests with react-testing-library. I’m buildilng a parallax component for my landing page. The component is passed the image via props and sets it via JSS as a background
Continue readingJest testing multiple test file port 3000 already in use
Issue I’m creating a testing for my express app. The project has multiple test files. In each module the server instance is required at beforeEach() method and closed at afterEach() method. but after testing one or two of the modules
Continue readingHow to test a Typescript function using jest?
Issue I am trying to write the tests for the typescript function using Jest and there are some complex case I am trying to test but I am not sure how. Example scenario, what would happen when a function that
Continue readingReact-scripts test: no traceback on exception
Issue I remake browser version of TacticToy game with React, and during unit-tests writing I’ve got a problem: there is no full traceback of a custom exception, only test function is highlighted: In the package.json file’s scripts section I have
Continue readingHow to stop a commit if test coverage is below a certain percentage?
Issue I’m using Jest to test a NestJS application and I’m trying to create a git hook with husky that will not allow a commit if tests coverage are under 95%, I haven’t tried anything yet cause I really don’t
Continue readingJest: to check if a function is called by a specific instance of class in JavaScript/Typescript
Issue I am testing some express middlewares with jest. it("should throw 400 error if request.body.id is null", () => { const req = { body: { id: null } } as any; const res = {} as any; const next
Continue readingTypescript paths not resolving when running jest?
Issue Attempting to convert this project over to jest using these instructions. I have everything working except for the files that use the paths configuration: “paths”: { “@fs/*”: [“./src/*”], “@test/*”: [“./test/*”] } It looks as if when the tests are
Continue readingQuery a simple button with jest and
Issue I’m trying to test my component, so here it’s : import React from ‘react’; import { useNavigate } from ‘react-router-dom’; import ‘../styles/mainPageStyles.css’; const MainPage = (): React.ReactElement => { const navigate = useNavigate(); const handleBeginQuiz = () => {
Continue readingHow do I mock an fs.writeFile call with a promise using jest?
Issue After trying many ways to do this, I’ve hit a brick wall. With the code I have now, once the fs.writeFile is dummied, the software throws the following error: Error: ENOENT: no such file or directory (followed by the
Continue readingHow to test NestJs response interceptor
Issue I tried to follow this thread but it I keep getting an error. transform-response.interceptor.ts: import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from ‘@nestjs/common’; import { Observable } from ‘rxjs’; import { map } from ‘rxjs/operators’; import { ApiResponseInterface }
Continue readingMocking a default export function with Jest: TypeError: (0 , _sampleFunction).default is not a function
Issue I have the following files: sampleFunction.ts: export default (x: number) => x * 2; testFile: import sampleFunction from ‘./sampleFunction’; export default () => { const n = sampleFunction(12); return n – 4; }; testFile.test.ts: import testFile from ‘./testFile’; const
Continue readingReact testing library: Test styles (specifically background image)
Issue I’m building a React app with TypeScript. I do my component tests with react-testing-library. I’m buildilng a parallax component for my landing page. The component is passed the image via props and sets it via JSS as a background
Continue readingMock 'S3' feature of 'aws-sdk' (nodeJS and Jest)
Issue I need to test a file in charge of retrieving data from S3 through the ‘aws-sdk’ (nodeJs + Jest). The file is: const AWS = require(‘aws-sdk’); let S3 = null; const getS3 = async () => { if (S3
Continue readingUpgrading Jest to v28 – Error Test environment jest-environment-jsdom cannot be found
Issue Has anyone successfully upgraded to latest Jest version 28.0.0? I’m receiving an error: Error: Test environment jest-environment-jsdom cannot be found. Make sure the testEnvironment configuration option points to an existing node module. Solution Jest team added more descriptive error
Continue readingHow can I test a property on an object that may be of two different types using Jest and TypeScript?
Issue I have a function getFruit() that returns two possible types, Banana | Apple. I have a jest unit test that includes a test for a property that exists on one of the types, but not the other. In this
Continue readingNestjs: cannot inject ConfigService while testing
Issue I’m having problems setting up a unit test that utilizes the ConfigService to set up TypeORM. The test below fails with the following message: Nest can’t resolve dependencies of the TypeOrmModuleOptions (?). Please make sure that the argument ConfigService
Continue readingWhy jest.fn() can be assigned to any function in Typescript?
Issue I’m confused how jest.fn() works in Typescript. For example class MyClass { myFunction() { return ‘hello’ } } let myClass = new MyClass() myClass.myFunction = jest.fn() From my understanding, myClass.myFunction has a type of ‘() => string’ but jest.fn()
Continue readingHow can I unit test that a guard is applied on a controller in NestJS?
Issue I’ve got a controller configured in NestJS and I want to check that the appropriate guards are set – does anyone have an example of how it could be done? This (abridged) example works correctly as an application so
Continue readingPostgres, Node, Jest – Splitting testes into two suites results in deadlock
Issue I have two suites of tests, one for Accounts and one for Transactions, accounts.spec.js and transactions.spec.js. I’m also using supertest. When I run them in jest, I get the error error: deadlock detected. But if I move all describe
Continue readingUncaught TypeError: Cannot read properties of undefined (reading 'isBatchingLegacy')
Issue I am trying to test a react typescript project using jest but it’s giving a confusing error: Error image Here is my package.json: "dependencies": { "@testing-library/jest-dom": "^5.16.4", "@testing-library/react": "^12.1.5", "@testing-library/user-event": "^13.5.0", "@types/jest": "^27.4.1", "@types/node": "^16.11.26", "@types/react": "^17.0.43", "@types/react-dom": "^17.0.14",
Continue readingCannot find module '@ngrx/effects' when running tests with Jest
Issue When trying to run tests with jest in our angular application I get the following message: Cannot find module ‘@ngrx/effects’ from ‘src/app/modules/core/core.module.ts’ It is weird, because the application runs and resolves this module without a problem, this error also
Continue readingJest test error: …subscribe is not a function
Issue I’m using Jest to test my Angular app (using Nx workspaces). I have a component that uses a service that I’m trying to mock. Here’s the code: myDummyService.permissions$.subscribe(permission => return // whatever); In my test I mock the service
Continue readingTypescript Build Fails When Adding Angular into Monorepo (Clashing of Jasmine and Jest Types)
Issue Gist I have a Monorepo with solely Typescript packages. When I run tsc –build all packages will be compiled to Javascript. This worked fine until I added a package containing an Angular app. For testing my packages I am
Continue readingHow to spy a class instantiated within beforeEach in Jest?
Issue I have a class instance that should be cleared between each test, so I’m doing this: class Foo { constructor() {} public bar() { return console.log("bar") } } describe(‘tests on class Foo’, () => { let foo: Foo beforeEach(()
Continue readingHow to see stacktrace / cause of an error in Jest?
Issue I’m trying to debug a nodeJS app. I have some code which causes an error, a variable is undefined. When I run the code normally, the error is very clear and easy to find: without jest: ➜ server git:(dc/build)
Continue readingRun Jest tests only for current folder
Issue I have Jest installed on my machine and typing jest from terminal results in tests from parent folers also getting executed. I want to run tests only from the current folder. For e.g. if I go to c:/dev/app in
Continue readingTS-Jest not resolving tsconfig paths
Issue I have already added these paths to tsconfig.json: { "compilerOptions": { "lib": ["ESNext"], "moduleResolution": "node", "noUnusedLocals": true, "noUnusedParameters": true, "removeComments": true, "sourceMap": true, "target": "ES2020", "outDir": "lib", "emitDecoratorMetadata": true, "experimentalDecorators": true, "baseUrl": ".", "paths": { "@lambdas/*": ["src/lambdas/*"], "@services/*": ["src/services/*"],
Continue readingJest won't accept top-level-awaits with NodeJS16 & TypeScript
Issue I’m trying to update my NodeJS12 & TypeScript app to Node16, one if the reasons is the need to use top-level-awaits. The code compiles correctly after the update, but Jest won’t accept the specific top-level-await code: ts-jest[ts-compiler] (WARN) src/xxx.ts:11:17
Continue reading