What is the process for integrating Mocha into a create-react-app project that uses Typescript?

I have been working on a react application using create-react-app (typescript) and found that I prefer using mocha + enzyme for testing my React components instead of jest.

In the past, I used the following test script:

"test" :"NODE_ENV=development mocha --watch-extensions tsx --watch --require ignore-styles --require babel-core/register ./src/*.test.tsx".

However, I encountered an issue where mocha was not recognizing the tsx files that I was importing.

Test Script:

"test": "NODE_ENV=development mocha -r babel-core/register -r ts-node/register src/*.test.tsx".

Error :

TSError: Γ¿» Unable to compile TypeScript
src\ComponentTest.test.ts (7,34): Parameter 'obj' implicitly has an 'any' 
type. (7006)
src\ComponentTest.test.ts (7,237): Property 'default' does not exist on type 
'{}'. (2339)
 at getOutput (E:\AssetWise\BeConnect_AssetWiseConncet\AssetWiseCONNECT\src\Client\assetwiseconnect\node_modules\ts-node\src\index.ts:330:15)
at Object.compile (E:\AssetWise\BeConnect_AssetWiseConncet\AssetWiseCONNECT\src\Client\assetwiseconnect\node_modules\ts-node\src\index.ts:518:11)
at Module.m._compile (E:\AssetWise\BeConnect_AssetWiseConncet\AssetWiseCONNECT\src\Client\assetwiseconnect\node_modules\ts-node\src\index.ts:403:43)
at loader (E:\AssetWise\BeConnect_AssetWiseConncet\AssetWiseCONNECT\src\Client\assetwiseconnect\node_modules\babel-register\lib\node.js:144:5)
at require.extensions.(anonymous function) (E:\AssetWise\BeConnect_AssetWiseConncet\AssetWiseCONNECT\src\Client\assetwiseconnect\node_modules\babel-register\lib\node.js:154:7)
at Object.require.extensions.(anonymous function) [as .ts] (E:\AssetWise\BeConnect_AssetWiseConncet\AssetWiseCONNECT\src\Client\assetwiseconnect\node_modules\ts-node\src\index.ts:406:12)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Module.require (module.js:579:17)
at require (internal/module.js:11:18)
at E:\AssetWise\BeConnect_AssetWiseConncet\AssetWiseCONNECT\src\Client\assetwiseconnect\node_modules\mocha\lib\mocha.js:250:27
at Array.forEach (<anonymous>)
at Mocha.loadFiles (E:\AssetWise\BeConnect_AssetWiseConncet\AssetWiseCONNECT\src\Client\assetwiseconnect\node_modules\mocha\lib\mocha.js:247:14)
at Mocha.run (E:\AssetWise\BeConnect_AssetWiseConncet\AssetWiseCONNECT\src\Client\assetwiseconnect\node_modules\mocha\lib\mocha.js:576:10)
at Object.<anonymous> (E:\AssetWise\BeConnect_AssetWiseConncet\AssetWiseCONNECT\src\Client\assetwiseconnect\node_modules\mocha\bin\_mocha:637:18)
at Module._compile (module.js:635:30)
at Object.Module._extensions..js (module.js:646:10)
at Module.load (module.js:554:32)
at tryModuleLoad (module.js:497:12)
at Function.Module._load (module.js:489:3)
at Function.Module.runMain (module.js:676:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3

Test file:

import * as expect from 'chai';
import * as React from 'react'; 
import * as enzyme from 'enzyme';
import App from './App';
import * as Adapter from 'enzyme-adapter-react-16';
enzyme.configure({adapter : new Adapter()});

describe('simple test with mocha', () => {
    it('should pass' , () => {
        // tslint:disable-next-line:no-unused-expression
        expect.expect(true).to.be.true;
    });
});

describe('testing react components', () => {
   const wrapper = enzyme.shallow(<App/>);
   expect.expect(wrapper.find('div')).to.have.length(1);  
 });

App component:

import * as React from 'react';
import './App.css';
const logo = require('./logo.svg');

class App extends React.Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <Sample/>
      </div>
    );
  }
}

export default App;

Answer №1

Here's an example of how you can approach this:

import * as assert from 'chai';
describe('calculate', function() {
    let mainAssert = assert.assert;

    it('addition', function() {
      let result = 5 + 2;
      mainAssert(result).equal(7);
    }); 
  });

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

Dispatch a websocket communication from a synchronous function and retrieve the information within the function itself

I am currently working on an Angular project and need guidance on the most effective approach to implement the following. The requirement is: To retrieve an image from the cache if available, otherwise fetch it from a web socket server. I have managed ...

What is the proper way to set up @Input?

I attempted to accomplish this in the following manner: @Input() data: any[] = []; Upon entering the ngOnInit lifecycle method, I notice that this.data is undefined: ngOnInit() { console.log(this.data); } Consequently, when trying to access th ...

It is not possible to access the Angular component using routing capabilities

I'm facing an issue with my Angular routing setup. I have two components, "view-emp" and "edit-emp", but only "edit-emp" is accessible for navigation. When I try to click on the link to navigate to "view-emp", nothing happens and I stay on the home sc ...

The variable in my NodeJS code is persisting across multiple requests and not being reset as expected

After setting up a project with the help of Typescript-Node-Starter, I have successfully created a controller and a route to call a specific function. import { Request, Response } from "express"; import axios from "axios"; import { pars ...

Properties for a standard React component

Currently, I am developing a form component in react with typescript that requires a 'fieldStructures' and an 'onSubmit' prop. type FieldStructure { type: 'text'; name: string; label?: string; helpText?: string ...

There seems to be an issue with the OpenAPI generator for Angular as it is not generating the multipart form data endpoint correctly. By default

Here is the endpoint that needs to be addressed: @PostMapping(value = "/file-upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public List<FileReference> handleFileUpload( @RequestPart(value = "file", name = "f ...

Ensuring thoroughness in validation without the use of specific text strings

Implementing the assignment or assertion of never at the end of a function is a strategy commonly used in Typescript to ensure exhaustive checks at compile time. To enable the compiler to recognize this, explicit strings are needed for it to check against ...

Watching the Event Emitters emitted in Child Components?

How should we approach utilizing or observing parent @Output() event emitters in child components? For instance, in this demo, the child component utilizes the @Output onGreetingChange as shown below: <app-greeting [greeting]="onGreetingChange | a ...

What is the correct way to include a JSON file in TypeScript?

Currently, I'm attempting to reference a JSON path and save it as a constant. My initial approach involved creating a reference with a string and then sending it back as a response using res.send, which successfully returned the string. However, I am ...

An error occurred: The property 'toUpperCase' cannot be read of an undefined Observable in an uncaught TypeError

Encountering an issue during the development of a mobile app using the ionic framework for a movie application. After finding an example on Github, I attempted to integrate certain functions and designs into my project. The problem arises with the 'S ...

When it comes to providedIn in Angular, which of 'root', 'platform', or 'any' is the preferred choice for different scenarios?

When it comes to providedIn in Angular, which option out of 'root', 'platform', 'any' should be the preferred choice in different cases? https://angular.io/api/core/Injectable 'root' : The application-level injec ...

Can HTML variables be accessed in lines of code before they are declared in HTML?

In line 1 of my code, I am trying to access the rowData variable which is declared in the second HTML line. However, I keep getting the error message "Property 'rowData' does not exist on type 'AppComponent'" for that line. Strangely, t ...

Using the `require('ts-node/register')` method for programmatic implementation in TypeScript

ts-node recommends using require('ts-node/register'). This is also evident in the angular2-webpack-starter Protractor configuration. What exactly does require('ts-node/register') do? Does it modify require to compile TS files, allowing ...

Ways to resolve the error message "Type 'Promise<{}>' is missing certain properties from type 'Observable<any>'" in Angular

Check out this code snippet: const reportModules = [ { url: '', params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() } }, { url: 'application1', params: { to: for ...

An error is triggered by the EyeDropper API stating that 'EyeDropper' has not been defined

I am trying to utilize EyeDropper for an eyedropper function in my project that uses Vue2 + Ts. Here is the code snippet: <div v-if="haveEyeDropper" @click="handleClickPick" > <i class="iconfont icon-xiguan"> ...

Utilizing the URL path name for data retrieval in Next.js 14 - A step-by-step guide

I'm currently developing a blog using AWS Amplify Gen 2 and GraphQL for a Next.js 14 project with TypeScript. As part of my application, I need to fetch specific data based on the URL path name. Here's how I've approached it: My approach in ...

Unlocking the potential of the ‘Rx Observable’ in Angular 2 to effectively tackle double click issues

let button = document.querySelector('.mbtn'); let lab = document.querySelector('.mlab'); let clickStream = Observable.fromEvent(button,'click'); let doubleClickStream = clickStream .buffer(()=> clickStream.thrott ...

Prevent the element attribute from being enabled before the onclick function is triggered

I am attempting to implement a feature in Angular that prevents double clicking on buttons using directives. Below is the pertinent code snippet from my template: <button (click)="onClickFunction()" appPreventDoubleClick>Add</button> And her ...

Tips for creating Material UI elements using React and Typescript

I am looking to extend a component from the Material UI library by creating a custom component that encapsulates specific styles, such as for a modal wrapper. However, I feel that my current solution involving the props interface may not be ideal. Is the ...

Leveraging TypeScript to share information between directives in AngularJS through asynchronous calls

Although I've found some scattered information on how to tackle this issue, I haven't been able to find a solid solution. In my AngularJS application, I have an asynchronous call that fetches data from a server and I need to store it in a variab ...