Encountering "Module ts-jest not found in the transform option" Error During Bazel Testing

In my working Bazel BUILD file, I have set up the following configurations:

package(default_visibility = ["//visibility:public"])

load("@io_bazel_rules_docker//nodejs:image.bzl", "nodejs_image")
load("@npm_bazel_typescript//:index.bzl", "ts_library")

# TODO run jest tests and stop build if test not passes
# TODO also run tests from dependent packages
load("@lbm//:jest.bzl", "jest_test")
jest_test(
    name = "test",
    srcs = glob(
        include = ["**/*.ts"],
    ),
    jest_config = "@lbm//:jest.config.js",
    deps = [
        "//packages/enums/src:lib",
        "//packages/hello/src:lib",
        "@npm//faker",
        "@npm//@types/faker",
        "@npm//express",
        "@npm//@types/express",
        "@npm//jest",
        "@npm//ts-jest",
        "@npm//@types/jest",
    ],
)

ts_library(
    name = "lib",
    srcs = glob(
        include = ["**/*.ts"],
        exclude = ["**/*.spec.ts"]
    ),
    deps = [
        "//packages/enums/src:lib",
        "//packages/hello/src:lib",
        "@npm//faker",
        "@npm//@types/faker",
        "@npm//express",
        "@npm//@types/express",
    ],
)

nodejs_image(
    name = "server",
    data = [":lib"],
    entry_point = ":index.ts",
)

load("@io_bazel_rules_docker//container:container.bzl", "container_push")

container_push(
   name = "push_server",
   image = ":server",
   format = "Docker",
   registry = "gcr.io",
   repository = "learning-bazel-monorepo/server",
   tag = "dev",
)

While the server builds successfully, the test fails to run.

Running

bazel test //services/server/src:test
results in the following output:

INFO: Analyzed target //services/server/src:test (0 packages loaded, 0 targets configured).
INFO: Found 1 test target...
FAIL: //services/server/src:test (see /home/flolu/.cache/bazel/_bazel_flolu/698f7adad10ea020bcdb85216703ce08/execroot/lbm/bazel-out/k8-fastbuild/testlogs
/services/server/src/test/test.log)
Target //services/server/src:test up-to-date:
  bazel-bin/services/server/src/test_loader.js
  bazel-bin/services/server/src/test.sh
INFO: Elapsed time: 0.947s, Critical Path: 0.72s
INFO: 2 processes: 2 linux-sandbox.
INFO: Build completed, 1 test FAILED, 2 total actions
//services/server/src:test                                               FAILED in 0.1s
  /home/flolu/.cache/bazel/_bazel_flolu/698f7adad10ea020bcdb85216703ce08/execroot/lbm/bazel-out/k8-fastbuild/testlogs/services/server/src/test/test.log

INFO: Build completed, 1 test FAILED, 2 total actions

The test.log file indicates the following issue:

exec ${PAGER:-/usr/bin/less} "$0" || exit 1
Executing tests from //services/server/src:test
-----------------------------------------------------------------------------
● Validation Error:

  Module ts-jest in the transform option was not found.
         <rootDir> is: /home/flolu/.cache/bazel/_bazel_flolu/698f7adad10ea020bcdb85216703ce08/sandbox/linux-sandbox/3/execroot/lbm/bazel-out/k8-fastbuild/bin/services/server/src/test.sh.runfiles/lbm/external/lbm

  Configuration Documentation:
  https://jestjs.io/docs/configuration.html

It appears that there is an issue with ts-jest. Running jest manually does not produce any errors.

My [jest.config.js][2] at the root of the project has the following configuration:

module.exports = {
  roots: ['<rootDir>/services/server/src', '<rootDir>/packages/hello/src'],
  testMatch: ['**/__tests__/**/*.+(ts|tsx|js)', '**/?(*.)+(spec|test).+(ts|tsx|js)'],
  transform: {
    '^.+\\.(ts|tsx)$': 'ts-jest',
  },
};

Feel free to try it out by cloning this repository: https://github.com/flolude/minimal-bazel-monorepo

Update 1

While attempting to implement the solution provided by @Charlie OConor, I encountered the following error:

services/server/src/util.spec.ts:1:21 - error TS2307: Cannot find module './util'.

1 import { add } from './util';
                      ~~~~~~~~

In order to resolve this, I added the util.ts file to the srcs like this:

srcs = glob(
    include = ["**/*.ts"],
),

However, this led to the following error:

ERROR: /home/flolu/Desktop/minimal-bazel-monorepo/services/server/src/BUILD:33:1: in args attribute of nodejs_test rule //services/server/src:test: label '//services/server/src:test_lib.js' in $(location) expression expands to more than one file, please use $(locations //services/server/src:test_lib.js) instead.  Files (at most 5 shown) are: [services/server/src/index.js, services/server/src/util.js, services/server/src/util.spec.js]. Since this rule was created by the macro 'jest_test', the error might have been caused by the macro implementation
ERROR: Analysis of target '//services/server/src:test' failed; build aborted: Analysis of target '//services/server/src:test' failed; build aborted
INFO: Elapsed time: 4.487s
INFO: 0 processes.

Answer №1

Revise Actual Problem

Upon further examination, I have decided to keep the previous response as it contains valuable information. The version of build_bazel_rules_nodejs you were using was outdated. I recommend updating it to the latest version, which is 1.0.1. The version you had installed, 0.42.2, may have caused issues with npm dependencies handling.

http_archive(
    name = "build_bazel_rules_nodejs",
    sha256 = "e1a0d6eb40ec89f61a13a028e7113aa3630247253bcb1406281b627e44395145",
    urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/1.0.1/rules_nodejs-1.0.1.tar.gz"],
)

Furthermore, ensure to update the "@bazel/typescript": "^1.0.1", line in your package.json to match the version. There may be compatibility issues with other dependencies in your repository as well. I managed to resolve them by excluding irrelevant docker configurations. Updating them should not be overly challenging.

Initial Response

While this may not be the answer you were anticipating, consider eliminating the use of ts-jest. Its purpose is to simplify the testing process by removing the need for a separate compilation step. In your case, since you are using Bazel to manage dependencies, you can define the dependency graph efficiently. This allows you to create a ts_library for your tests and then utilize the output in jest_test.

Include a new tsconfig.test.json file with the following content:

{
  "extends": "./tsconfig.json",
  "lib": ["jest"]
}

This configuration ensures correct type checking with jest-specific features like describe() and it().

To combine the two tsconfigs.json, utilize ts_config. Place the following code in your /BUILD file:

load("@npm_bazel_typescript//:index.bzl", "ts_config")
ts_config(
    name = "tsconfig.jest.json",
    src = "tsconfig.test.json",
    deps = [
        ":tsconfig.json",
    ],
)

Create a ts_library for your tests and specify the output for use in jest_test:

load("@npm_bazel_typescript//:index.bzl", "ts_library")
ts_library(
    name = "test_lib",
    srcs = ["util.spec.ts"],
    tsconfig = "//:tsconfig.jest.json",
    deps = [
        "//packages/enums/src:lib",
        "//packages/hello/src:lib",
        "@npm//faker",
        "@npm//@types/faker",
        "@npm//express",
        "@npm//@types/express",
        "@npm//cors",
        "@npm//@types/jest",
    ],
)

filegroup(
    name = "test_lib.js",
    srcs = [":test_lib"],
    output_group = "es5_sources",
)

load("@lbm//:jest.bzl", "jest_test")
jest_test(
    name = "test",
    srcs = [
        ":test_lib.js",
    ],
    jest_config = "@lbm//:jest.config.js",
    deps = [
        ":lib",
        "//packages/enums/src:lib",
        "//packages/hello/src:lib",
        "@npm//faker",
        "@npm//express",
        "@npm//jest",
    ],
)

These rules may seem repetitive, so you could consider encapsulating them into generic rules for easier management.

I have reviewed your code and am unable to pinpoint why ts-node is not functioning as expected. Its inclusion in

jestconfig.js</code demonstrates that the dependency is present. It is possible that the issue lies within <code>jest
or ts-jest, although I have not found any definitive answers.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Next.js build encountered an error - unable to locate function in next/script module

While constructing a CMS using next.js, one of the key components is media management through Cloudinary. The integration of the Cloudinary Media Library widget was successful during development using next/script. However, an error has now emerged that pre ...

I'm experiencing an issue with my Next.js Airbnb-inspired platform where I am unable to save a listing to my favorites

While working on my Next.js Airbnb clone project, I encountered an issue with adding a Listing to favorites. The heart button component's color does not change when clicked, despite receiving a success response. Moreover, the addition to favorites is ...

Encounter a Typescript error when dealing with "app.ws" while using express-ws

I have a small project in mind where I want to create a BabyCam that can be accessed from any web browser using a Raspberry Pi Zero. My plan is to set up a web socket using express-is to stream video to multiple clients. I'm utilizing the raspivid-str ...

Showing nested routes component information - Angular

I am working on a project that includes the following components: TodosComponent (path: './todos/'): displaying <p>TODO WORKS</p> AddTodosComponent (path: './todos/add'): showing <p>ADD TODO WORKS</p> DeleteTo ...

Steer clear of mentioning unbound methods, as they can lead to accidental scoping errors with 'this' when invoking static methods

I've been working on a method map based on a query from the Stack Overflow post linked here to assist me in dynamically calling a static method. But, I keep encountering this error message: Avoid referencing unbound methods that could lead to uninte ...

The code below is not working as it should be to redirect to the home page after logging in using Angular. Follow these steps to troubleshoot and properly

When looking at this snippet of code: this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}}); An error is displayed stating that "Property 'url' does not exist on type '(name: string, styles: AnimationStyleMetadata". ...

Instances of servers, jest, and encountering the error message 'listen EADDRINUSE :::3000'

Hello, I am a beginner with jest, node and express, and I've encountered an issue while trying to test my application. While the code itself appears to be functional, I seem to be running into port blocking issues when passing the server instance to ...

Tips for explaining the structure of a basic Just functor in TypeScript

I am embarking on my first attempt to create a simple interface in TypeScript, and I find myself questioning every step along the way. The core question that troubles me is: How can I best describe this straightforward Jest matcher extension? /** * @par ...

Steer clear of using enum values in typescript to prevent potential issues

I am looking to iterate through an enum type in order to populate options within a react component. Below, you will find the specific enum and a function that retrieves its keys and values. export enum TaskType { daily, weekly, monthly, yearly } ...

Develop a PDF generator in ReactJS that allows users to specify the desired file name

Is there a way to customize the file name of a generated PDF using "@react-pdf/renderer": "^2.3.0"? Currently, when I download a PDF using the toolbar, it saves with a UID as the file name (e.g., "f983dad0-eb2c-480b-b3e9-574d71ab1 ...

What is the process for creating a nullable column in TypeORM?

Within my User entity, there is an optional column for the user's avatar image: @Entity() export class User { @PrimaryGeneratedColumn('uuid') id: string @Column({ unique: true }) email: string @Column({ unique: true }) ...

Creating objects based on interfaces in TypeScript is a common practice. This process involves defining

Within my TypeScript code, I have the following interface: export interface Defined { 4475355962119: number[]; 4475355962674: number[]; } I am trying to create objects based on this interface Defined: let defined = new Defined(); defined['447 ...

Convert an interface type variable to a string representation

I'm just starting to learn angular and I'm attempting to convert my response from an interface type into a string so that I can store it in session storage. However, when I try to save them, they are being stored as [object] in the session storag ...

Identify an icon within a chip label - conducting testing with React Jest

In my current project, I am working on a React app with Material UI. One of the components involves generating multiple Chip elements by iterating through some maps (the values index1, index2, and value</code are obtained from these maps). When a user c ...

How to send a variable to Firestore query in an Angular application

I'm attempting to retrieve data from a schedule collection based on a field matching the user's id. However, I'm encountering an issue with the error message: "Function Query.where() requires a valid third argument, but it was undefined." ...

The error message "Property 'originalUrl' is not found in type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'" appeared

In my TypeScript project, I am utilizing a gulpfile to initiate the process. Within the gulpfile, I am using express where I encounter an issue while trying to access req.originalUrl, with req being the request object. An error is thrown stating Property ...

Sending variables from a main page to a nested component

Currently facing an issue with the routing mechanism in Angular 9. Specifically, I am struggling to capture the parameter inside the BuildingDetailComponent even though it is present in the URL displayed in the address bar. In the Parent component, my rou ...

ngx-datatable detail row failing to expand properly

I am striving to develop an ngx-datatable component that can be utilized universally for consistent styling and functionality. Although most features are working correctly, I'm struggling to understand why the details row isn't expanding as expe ...

Creating Beautiful MDX Layouts with Chakra UI

Currently, I am attempting to customize markdown files using Chakra UI within a next.js application. To achieve this, I have crafted the subsequent MDXComponents.tsx file: import { chakra } from "@chakra-ui/react" const MDXComponents = { p: (p ...

An exception is thrown by TypeScript's readline.createInterface function

My current project involves creating an electron app. I am facing an issue in the main.ts file where I have constructed a seemingly simple class with a constructor that is not running as expected. The problem arises when the call to readline.createInterfac ...