The error TS2304 occurs when the e2e tsconfig types cannot find the name 'browser'

I am facing challenges while setting up a sample angular project with a basic webdriverio end-to-end test, encountering some compilation errors in my e2e test.

Setting up tsconfig

The project is configured with the following key files:

e2e / test / [e2e test code]
e2e / tsconfig.e2e.json
e2e / wdio.conf.js
package.json
tsconfig.json

Here's how my base tsconfig.json appears:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2018",
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

And here's how the tsconfig.e2e.json looks like:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "module": "CommonJS",
    "outDir": "../dist/out-tsc/e2e",
    "baseUrl": "./",
    "target": "es2018",
    "types": [
      "node",
      "@wdio/sync",
      "@wdio/jasmine-framework",
      "jasminewd2"
    ]
  }
}

Output Errors

When running tsc from my IDE terminal or trying to execute the e2e script from package.json, I encounter the following compilation errors:

[0-0] 2021-02-09T15:47:53.019Z WARN @wdio/jasmine-framework: Unable to load spec files quite likely because they rely on `browser` object that is not fully initialised.
`browser` object has only `capabilities` and some flags like `isMobile`.
Helper files that use other `browser` commands have to be moved to `before` hook.
Spec file(s): C:\dev\source\rme\angular-wdio6-builder-demo\e2e\test\specs\basic.spec.ts
 Error:  TSError: ⨯ Unable to compile TypeScript:
e2e/test/specs/basic.spec.ts(7,5): error TS2304: Cannot find name 'browser'.
e2e/test/specs/basic.spec.ts(8,19): error TS2304: Cannot find name 'browser'.
e2e/test/specs/basic.spec.ts(13,5): error TS2304: Cannot find name 'browser'.
e2e/test/specs/basic.spec.ts(14,21): error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`.

Assumption and Minimized Reproducible Example

I suspect that during the compilation of my e2e code, the contents of `tsconfig.e2e.json` are somehow being ignored as it fails to recognize the `browser` object specified in the types reference `@wdio/sync`.

A detailed Minimal Reproducible Example (MRE) can be accessed here on GitLab, which was inspired by this question. The CI script also displays the error output that occurs locally.

Additionally, note that my IntelliJ IDE correctly references the `browser` object and clicking on it shows that the browser variable is located in the `node_modules\@wdio\sync\webdriverio.d.ts` file.

Additional Update: In the package.json, there is a pree2e script executed before e2e, calling e2e/e2e.cmd:

set TS_NODE_PROJECT=e2e/tsconfig.e2e.json

Second Update: the wdio.conf.js Configuration File:

The complete file along with generated comments is also available in the minimal reproducible example: e2e/wdio.conf.js

exports.config = {
    runner: 'local',
    path: '/',
    specs: [
      `${__dirname}/test/specs/**/*.ts`
    ],
    exclude: [
    ],
    maxInstances: 10,
    capabilities: [{
        maxInstances: 5,
        browserName: 'chrome',
    }],
    logLevel: 'warn',
    bail: 0,
    baseUrl: `http://localhost:${process.env.PORT || 4200}`,
    waitforTimeout: 10000,
    connectionRetryTimeout: 90000,
    connectionRetryCount: 3,
    services: ['chromedriver'],
    framework: 'jasmine',
    jasmineNodeOpts: {
        requires: ['ts-node/register'],
        defaultTimeoutInterval: 60000,
        expectationResultHandler: function(passed, assertion) {
            // do something
        }
    },
}

Answer №1

To incorporate ts-node into your wdio.conf file, make sure to include the following code in your jasmine options:

const tsNode = require('ts-node');
tsNode.register({
  files: true,
  project: './e2e/tsconfig.e2e.json'
});

exports.config = {
....
    jasmineNodeOpts: {
        // Make sure to require tsconfig-paths
        requires: ['tsconfig-paths/register'],
...
};

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

iterating over a nested map within a map in an Angular application

I wrote a Java service that returns an observable map<k, map<k,v>> and I'm currently struggling to iterate through the outer map using foreach loop. [...] .then( (response: Package) => { response.activityMap.forEach((key: s ...

Issue with Angular deployment via Azure DevOps results in failure to load, displaying a "hello to all node developers!" page instead

I am currently facing an issue while attempting to deploy my angular app on Azure. Despite a successful deployment and correct artifacts, when I visit the website, I am greeted with the default Azure "hey node developers" page. You can view the site here. ...

The initial values of Typescript class members are merged directly into the class constructor

This issue has been well documented (check out Initializing variables inline during declaration vs in the constructor in Angular with TS on SO for reference), but it can lead to challenging memory problems. Take a look at the example below class Bar { ...

Implementing SAML Authentication in Angular and .NET WebAPI

I am in the process of setting up a website that utilizes Angular for the user interface, .NET for the backend APIs, and integrates SAML for authentication with a third-party Azure AD. I'm finding it challenging to grasp how each component interacts w ...

It can be time-consuming to render a large quantity of dynamic markers on Leaflet after receiving a response

Incorporating leaflet.js into my web project, I am faced with the challenge of creating a map view with dynamic markers. Upon receiving a response, I attempt to generate dynamic components based on the data and utilize change detection to monitor updates. ...

What is the best way to import a TypeScript file in index.js?

I've recently developed an application using the react-express-starter template. I have a "server" directory where the backend is created by nodejs, containing an index.js file: const express = require('express'); const app = express(); c ...

Different or improved strategy for conditional rendering in Angular

Hey there! I've got a few *NgIf conditions in my template that determine which components (different types of forms) are displayed/rendered. For example, in one of my functions (shown below) private _onClick(cell:any){ this._enableView = fals ...

Undefined Perception

Trying to obtain values from an observable, my subscription code within the component looks like this: this.checkoutService.getDisabledDate().subscribe (dates=>{this.formattedDate=dates}, (error:any)=>{console.log(error)}); When logging this.forma ...

The error message "SyntaxError: Cannot use import statement outside a module" popped up while working with discord.js, typescript, heroku

// Necessary imports for running the discord bot smoothly import DiscordJS, { TextChannel, Intents, Message, Channel, NewsChannel, ThreadChannel, DiscordAPIError } from 'discord.js' type guildTextBasedChannel = TextChannel | NewsChannel | ThreadC ...

How can I use Laravel to enter data using the post method?

I've been struggling with data transfer in my Angular component for a while now, specifically using a post method. Despite extensive research and reading various documents, I haven't been able to find a solution. Can you assist me with this issue ...

What steps can I take to troubleshoot and fix the issue of a Duplicate identifier 'DateType' error during the React/Typescript building process

Utilizing the MUI library, I have also installed the @mui/x-date-pickers library. In order for my datepicker component to function properly, I need to install the @date-io/date-fns/ library as well. However, upon running yarn build, I encountered the fol ...

Ways to implement useState in a TypeScript environment

Hello, I am currently using TypeScript in React and trying to utilize the useState hook, but encountering an error. Here is my code: import React , { useState } from "react"; interface UserData { name: string; } export default function AtbComponent( ...

Guide to showcasing an image obtained from a Web API in Angular

I have a unique challenge with displaying images on the user interface. The image data is retrieved from a database through a web API, and the image path is stored in the DB's imagePath column. However, when fetching the data via the web API, only the ...

React application facing a problem with bracket notation in Typescript

After creating a form state to store and update input changes, I encountered an issue: const [form, setForm] = useState({ user: '', email: '', password: '', }); I then wrote a function to handle form changes: const handle ...

Issue with TypeScript retrieving value from an array

Within my component.ts class, I have defined an interface called Country: export interface Country{ id: String; name: String; checked: false; } const country: Country[] = [ { id: 'India', name: 'India', checked: false}, { ...

What is the method for locating an element within an array?

The content being returned is presenting a challenge. How can I retrieve data from inside 0? I attempted to access it using date[0] without success const { data } = getData(); The result of console.log(data) is shown below: enter image description here ...

What could be causing the HTTP PUT requests to stop functioning properly after a number of requests?

Currently, I am developing an app for the premier league that allows users to create their own teams, input scores for matches, and view updated team statistics in a sortable table based on the Premier League rules. Issue: I have encountered a problem wi ...

Is it possible to navigate to the Angular component that defines a tag in VSCode by simply clicking on the tag?

In my current Angular project in VSCode, I often find myself wanting to delve deeper into specific tags that I encounter while coding. For instance, if I stumble upon a tag like <display-active-users>, I usually have to go through the process of sea ...

Troubleshooting CORS problem: Angular 2 and AspNetCore WebApi encounter error with preflight response having invalid HTTP status code 401

Hello there! I am currently working on implementing a straightforward token based authentication method in an Angular 2 RC6 application against an AspNetCore WebApi project that I developed using Visual Studio 2015. If you're interested, I have uploa ...

What is the best way to incorporate the async pipe into my codebase when working with GraphQL queries?

I am currently working on an Angular project where I utilize GraphQL to fetch data in my component. In the HTML code, I display an image of the result. However, I encountered an error in the console that said: ERROR TypeError: Cannot read property 'im ...