Questions tagged [jestjs]

Jest, a unit testing framework developed by Facebook, greatly leverages Jasmine while offering the convenience of automated mock creation and a jsdom environment. This powerful tool is widely employed for efficiently testing React components.

Creating JEST unit tests for a basic functionality

Here is the React code I have written: getDetails: function () { var apiUrl = ConfigStore.get('api') request .get(apiUrl) .set('X-Auth-Token', AuthStore.jwt) .set('Accept', 'application/json') ...

What is the correct way to pass the res object into the callback function of a jest mock function?

Currently, I am working on developing a web server using Node.js and am in the process of ensuring comprehensive test coverage with Jest. One specific function, logout, requires testing within the if statement where it checks for errors. // app.js functio ...

What is the best way to run tests on this code using Jest?

Currently deep diving into ReactJS testing and struggling to tackle the component showcased below https://i.stack.imgur.com/jaEis.png Running jest with coverage reveals a gap from line 8 to 10 despite using data-testid for test execution, which seems pecu ...

How can we replicate user input in React for unit testing purposes?

Struggling to unit test a React component that accepts user input, specifically the onChange function within the component. Unable to set the input value despite trying various methods found online. Below is the component under test: class Input extends C ...

Changing return values with Jest mocks in TypeScript

Here I am again with a very straightforward example. In summary, I require a different response from the mocked class. Below is my basic class that returns an object: class Producer { hello() { return { ...

Exploring a custom hook with Jest testing

I have developed a custom hook that can display a notification message and automatically remove it after 2 seconds. I am looking to write a test for this functionality, but as someone new to writing tests, I'm unsure of the best approach. Can anyone provid ...

How to simulate axios in a vue3 typescript unit test with jest and vue-test-utils2 (Resolved)

When my component is mounted, it makes a call to this.axios.get() and passes a vuex-store variable to the API. The API responds with an array, which the component then displays after transitioning from a loading element. In my unit test, I want to simulat ...

Exploring unit testing service call responses using Jest with promises, along with the useEffect and useState hooks

I am currently facing some challenges with testing the useEffect function in jest. Within a react functional component, I need to mock values and return them when the serviceFn is called. The data returned should then be updated in the state. //from servic ...

Exploring the Capabilities of Connected Container Functions through Jest and Enzyme Testing

I am currently working with a connected container that looks like this: import React from 'react'; import PropTypes from 'prop-types'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux&apos ...

Using Jest or Mocha alongside Vue: Uncaught SyntaxError: Cannot use import statement outside a module

Update: This post has undergone multiple edits, please refer to this new Stackoverflow post for a clearer explanation of the issue: SyntaxError: Cannot use import statement outside a module when following vue-test-utils official tutorial I have been searc ...

Facing issues with dynamic imports in Jest and React Testing Library while testing Next.js 12? Try using SWC instead of babel for a smoother experience

I am encountering issues with testing dynamic imported components in Next.js 12. Here is some technical information: Next.js 12 uses SWC instead of Babel React 18 Jest + React Testing Library Below is an example: import styles from '@/pages/index.mo ...

Experimenting with React component functionality using Enzyme and Jest

Currently, I am in the process of testing a component that follows the Container/Presentational pattern. To achieve 100% coverage, I need to test the handleChange() function which contains a setState() method. The challenge lies in the fact that I am only ...

Prior to the ngAfterContentInit hook being triggered, simulate class members

I am facing an issue with a component that queries its content child. Here's the code snippet: @ContentChild(InputControlDirective, { read: ElementRef }) public inputControl: ElementRef; To handle this, I have implemented the ngAfterContentInit hook which ...

Jest and Enzyme failing to trigger `onload` callback for an image

I'm having trouble testing the onload function of an instance of the ImageLoader class component. The ImageLoader works fine, but my tests won't run properly. Here's an example of the class component: export default class ImageLoader extends React.Compone ...

ts-jest should replace the character '@' with the '/src' folder in the map configuration

I have set up a node project using TypeScript and configured various paths in my tsconfig.json file, such as: "paths": { /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ ...

Unit testing with Jest in TypeScript for mocking Express and Mongoose

I've been struggling to find comprehensive resources on using jest.fn() to mock TypeScript classes and their methods, like express' Request, Response, NextFunction, and the save() method on a mongoose model. For instance, suppose I have the following mode ...

Is there any way I can verify the invocation of signOut in this Jest test case?

I am attempting to perform testing on my home page within a next app. However, I have encountered an issue with a button in the Home component that triggers a logout firebase function. Despite my attempts to mock this function and verify whether or not i ...

Testing the combination of Angular units with combineLatest

Recently, I delved into unit testing using the Jest Framework in Angular. However, I've encountered a roadblock while trying to write unit tests for the combineLatest RxJS operator. Check out my component below: Component: public userData; public pro ...

What is an example scenario where Async Storage can be tested using Jest-expo?

To better understand the testing of Mock-async-storage for reactjs, I decided to replicate an example. If you have any suggestions on a different approach to testing, please feel free to share. I attempted to mimic a use case illustrated on this stack over ...

Discovering the status of a wrapped component using Jest

const wrapper = mount( <ContextProvider> <FreeformEquationQuestionPractice question={question} /> </ContextProvider> ) console.log('freeform state: ', wrapper.childAt(0).instance().state) FreeformEquationQuestionPracti ...

A problem with mocking arises when two modules share identical names

Within the setup.js file of Jest configuration, I have mocked two modules: jest.mock('somePath1/Translator'); jest.mock('somePath2/Translator'); Upon running tests, I encounter the following issue: jest-haste-map: duplicate manual mock found: Module n ...

Tips for using jest.mock with simple-git/promise

I have been attempting to simulate the checkout function of simple-git/promise in my testing but without success. Here is my current approach: jest.mock('simple-git/promise', () => { return { checkout: async () => { Promi ...

Tips for shutting down an Express server within the Jest afterAll hook

I am currently facing an issue with my Express server integration tests using Jest. To prevent port collisions between different test suites running in parallel, I am utilizing the get-port library to find random available ports. Although all my tests are ...

Don't forget to include the line 'import "reflect-metadata"' at the beginning of your entry point for Jest tests

As I work on developing an application using dependency injection with tsyringe, I came across a case where a service receives the repository as a dependency. Here is an example: import { injectable, inject } from 'tsyringe' import IAuthorsRepository from ...

Using Jest's moduleNameMapper with Next.js without TypeScript

I've been encountering some challenges trying to implement moduleNameMapper in NextJS using JavaScript. In this particular project, TypeScript is not being utilized. Next: 12.2.5 React: 18.2.0 Jest: 29.0.1 Jest environment jsdom: 29.0.1 Below is the cont ...

When using npm install, nested dependencies may not be installed automatically. However, you can explicitly install them to

In my custom package located at https://github.com/Voitanos/jest-preset-spfx, I have specified the following dependencies: "dependencies": { "@types/jest": "28.1.4", "identity-obj-proxy": "3.0.0", &qu ...

Try out Vue components with Jest and vue utilities

Trying to run a test on a vue component using jest and vue-utils is resulting in the following error: expect(jest.fn()).toHaveBeenCalled() Expected mock function to have been called, but it was not called. The component in question is the RandomPhoneNu ...

What is the best way to manage tables with a ManyToOne relationship in TypeORM when it comes

I have a scenario where I am working with two entities that have a ManytoOne relationship between them: The entities involved are: PersonalProfile Language Their relationship is defined in the code snippet below: import BaseModel from "@models/Base ...

An uncommon token was found by Jest - import (Angular CLI 6)

Struggling to get jest installed and running in an angular/cli (v6) app on Mac. Despite trying various methods to set up jest, I keep encountering the following error: Test suite failed to run Jest encountered an unexpected token This usually me ...

Testing Content Rendered in a Modal or Popover using React, Jest, and Material-UI

Some material-ui components, such as Dialog and Menu, do not render their results in the same location as where they are placed by their parent component. Due to this behavior, testing for the presence of content within these components becomes challengin ...

`The error "mockResolvedValue is not recognized as a function when using partial mocks in Jest with Typescript

Currently, I am attempting to partially mock a module and customize the return value for the mocked method in specific tests. An error is being thrown by Jest: The error message states: "mockedEDSM.getSystemValue.mockResolvedValue is not a function TypeEr ...

Check the feature that retrieves data from a `json` file

In my util file, I have a function that imports and checks whether a given sectionUUID has a video in the JSON file. import multipleVideos from '../data/videos.json' function hasSectionMultipleVideos (sectionUUID) { return multipleVideos.vide ...

Guide to efficiently testing the onChange event for a ui-material TextField component with Jest and Enzyme

I am a beginner in testing and struggling to test the changing value in the TextField component export const ParentComponent = ({ question, onValueChange }: ParentProps) => { const [value, setValue] = useState(default); const on ...

TypeError: Unable to find TextEncoder in mongoose and jest when using TypeScript

Currently, I am working on a project using Node 14 along with Express v4.16.3 and Typescript (v4.7.4). Recently, I added Mongoose (v6.5.2) to the project, and while the logic code seems fine, most of the tests executed by Jest (v26.4.2) are failing with th ...

Testing Angular combineLatest with Jest

I'm encountering a challenge in an assessment involving a complex Statement related to combineLatest. Here is the snippet of code: component: export class ErinnerungenErinnerungenComponent implements OnInit, OnDestroy { ... erinnerungen: ErinnerungM ...

Employing DOM manipulation within Vue unit tests as a last resort

What steps should I take to update my unit test in order to accurately validate the following scenario? Method: close(event) { const element = !!event?.target?.closest('#target') if (!element) { this.isVisible = false } }, Jest test: ...

"Unable to execute validateOptions as it is not a recognized function

ERROR src/pages/trade/trade-sagas/trade-sagas.unit.test.js ● Test suite failed to run Cannot locate module 'axios' from 'src/pages/trade/trade-sagas/trade-sagas.unit.test.js' 1 | import { runSaga } from "redux-saga"; &g ...

Discover the solution for seamless integration of TypeScript with the novel `exports` and `main` field

I am currently utilizing Node.js version 16.10.0 along with TypeScript 4.5.5. As part of my development process, I am in the midst of publishing a library and have implemented the following configuration: "main": "./dist/index.js", ...

Implement Stripe API mocking using Jest in Node.js with Typescript

I'm having trouble simulating the Stripe API for testing purposes. Although I don't have much experience with mocking functions using jest, I've already extensively researched how to mock the Stripe API without success. My file structure is as follows: sr ...

A guide on simulating an emit event while testing a Vue child component using Jest

During my testing of multiple child components, I have encountered a frustrating issue that seems to be poor practice. Each time I trigger an emit in a child component, it prompts me to import the parent component and subsequently set up all other child co ...

What is the best way to run tests on this method using Jest?

import { format, getDaysInMonth, getMonth, getYear, isValid, parse } from "date-fns"; export class DateService { public getDaysInMonth(month?: Date) { return getDaysInMonth(month || new Date()); } What is the best way to test this func ...

Setting up TypeScript in Jest without the need for webpack

Currently, I'm developing an NPM module using TypeScript without the use of Webpack for compiling scripts. I need some guidance on configuring Jest to properly run tests with TypeScript files. Any recommendations? // test.spec.ts import {calc} from ...

Testing asynchronous errors with Sequelize and Postgres

Recently, I've been working on writing unit tests for Sequelize with a Postgres database and using Jest for testing. While trying to get the following code to work: test('email field only takes valid emails', () => { expect.assertions( ...

"Exploring the world of jest.doMock: A guide to mocking

Here is the code snippet I am testing: ... import data from '../data/mock.json'; // function is async export const something = async () => { try { ... if (!data) { throw 'error is here!'; } return data; ...

After applying array.map, Material UI ToggleButton does not display correctly with either Jest or React Testing Library. It was functioning properly before the array.map was implemented. What could

Code Testing: import { render, screen } from "@testing-library/react"; import App from "../App"; test("The 2nd button is rendered", () => { render(<App />); expect(screen.getByRole("button", { name: &qu ...

Testing a component with React Testing Library and Jest while passing a boolean value: step-by-step guide

I am currently testing the visibility of the logout link for users who are logged in. The value I pass in the test determines whether the user is logged in or out. The isAuthenticated parameter is a boolean: true means the user is logged in, false means th ...

The method wrapper.setValue() is not suitable for use on EL-INPUT

Attempting to call a Vue component for unit testing with Jest, trying to set a value in an input text field. Below is the content of my "file.vue" file: <el-form-item label="Nombre" data-test="id-form"> <el-input v ...

Testing abstract class methods in Jest can ensure full coverage

In my project, I have an abstract generic service class. export default abstract class GenericService<Type> implements CrudService<Type> { private readonly modifiedUrl: URL; public constructor(url: string) { this.modifiedUrl = ...

Challenges encountered during the execution of React tests: Enzyme, Jest, and React integration

Encountered an error while running tests: FAIL src/components/common/user/UserMenu/__tests__/UserMenu.test.js ● Runtime Error Error: Failed to get mock metadata: /redacted-directory/node_modules/core-js/library/modules/_global.js See: http://facebook ...

Difficulty arises when Jest tests struggle to interpret basic HTML tags within a React Component

When running test runs, issues arise when using standard HTML tags with Jest. My setup includes Babel, Webpack, Jest, and React Testing Library. To enable jest, I have installed a number of packages: "@babel/plugin-proposal-class-properties": "7.8.3", "@ ...

Jest is not producing any output at all when executing tests

Below is a snapshot of my package.json: "jest": { "cacheDirectory": "/tmp/jestCache", "scriptPreprocessor": "node_modules/babel-jest", "modulePaths": [ "<rootDir>/app/static/react/" ], "moduleDirectories": [ "node_modules" ...

Ways to verify function arguments within an asynchronous function using Jest

I have a function that needs to be tested export const executeCommand = async ( command: string ): Promise<{ output: string; error: string }> => { let output = ""; let error = ""; const options: exec.ExecOptions = { ...

How can I configure a mocked dependency in Jest to return a specific value in a function?

I am currently working on simulating a mongoose model to facilitate unit testing for an express controller. To keep things simple, I've removed all unnecessary code and provided below the specific scenario I'm dealing with. Here's the snippet of the code t ...

Supporting multiple types for matching object structures is a feature in Jest

I'm currently working on a test using jest to verify if an object key is either a string or a number. It seems like a basic task, but surprisingly there isn't much guidance in the documentation. Test Example: test('Checking asset structure ...

Testing Vue's disabled input using Vuetify

Learning testing is a new challenge for me, and I'm navigating my way through the complexities of it. Today, I want to create a test for a Vuetify <v-text-field> component with the following structure: <v-text-field v-model="user.captio ...

Why is Jest not providing any test coverage when executed through npm?

I'm attempting to retrieve code coverage data for a specific Vue component using Jest. Suppose my component is located at /var/www/html/path/to/Component.vue and its corresponding unit test file can be found at /var/www/html/path/to/tests/unit/Component.s ...

Guide to simulating a function using .then within a hook

I am using a function that is called from a hook within my component. Here is my component: ... const handleCompleteContent = (contentId: string) => { postCompleteContent(contentId, playerId).then(data => { if (data === 201) { ... The caller ...

Jest came across a surprising token that it wasn't expecting while working with React and TypeScript in conjunction with Jest and React-testing-L

An unexpected token was encountered by Jest while using React and TypeScript along with Jest and React-testing-Library. Error occurred at: E:\Git\node_modules@mui\x-date-pickers\internals\demo\index.js:1 ({"Object." ...

issues arise with tests following the transition from Angular 9 to Angular 10

Recently, I encountered an issue with my jest-tests after updating Angular from version 9 to 10. These tests were working perfectly fine before the update. Can someone guide me on how to resolve this issue? Below is one of the tests that is causing troubl ...

Here is a unique version: "Exploring the process of implementing act(...) for second, deferred,

I am currently working on a component that looks like this: function MyCustomComponent(props) { const [items, setItems] = useState([]); useEffect(() => { loadItems(); }, []); async function loadItems() { const result = await axios. ...

Jest's JavaScript mocking capability allows for effortless mocking of dependent functions

I have developed two JavaScript modules. One module contains a function that generates a random number, while the other module includes a function that selects an element from an array based on this random number. Here is a simplified example: randomNumbe ...

Im testing the creation of a global style using styled-components

Is there a way to create snapshot tests for styled-components with createGlobalStyle? The testing environment includes jest v22.4.4, styled-components v4.1.2, react v16.7, jest-styled-components v5.0.1, and react-test-renderer v16.6.3 Currently, the outp ...

Utilize a function to wrap the setup and teardown code in Jest

I am attempting to streamline some common setup and teardown code within a function as shown below: export function testWithModalLifecycle() { beforeEach(() => { const modalRootDom = document.createElement('div') modalRootDom.id = ModalRootDo ...

Snapshots testing app Expo TypeScript Tabs App.tsx

After setting up an Expo project with Typescript and Tabs, I decided to add unit testing using Jest but ran into some issues. If you want to create a similar setup, check out the instructions here: . Make sure to choose the Typescript with Tabs option whe ...

Attempting to use vue-test-utils-getting-started with the standard configuration results in a "Preset Not Found" error during

Currently, I am in the process of conducting a unit test by referring to the official guide provided. To do so, I have cloned the demonstration repository named vue-test-utils-getting-started. To replicate the issue, follow these steps: After cloning vu ...

Jest encounters an issue while attempting to import Primeng CSS files

I am currently utilizing Jest version 26.6.3 for testing Angular components. Unfortunately, the unit tests for components that utilize Primeng's checkbox component are failing during the compileComponents step with the error message "Failed to load checkbo ...

How can we check for the presence of the string '...loading' in a React component that utilizes styled-components?

Looking for tips on writing jest enzyme assertions for styled components? Typically, my test setup includes the following: import React from 'react'; import { shallow } from 'enzyme'; // test-setup.js import { configure } from 'e ...

What are the limitations of jest and jsdom in supporting contenteditable features?

I am facing an issue with a particular test case: test('get html element content editable value', () => { // arrange const id = 'foo'; document.body.innerHTML = `<div id='${id}' contenteditable="true">1</div>`; // act const elem ...

The component cannot be created using shallowMount because vm.$refs['VTU_COMPONENT'] is not defined

Not sure if it's a bug or if I'm making a mistake. I attempted to use shallowMount to mount my main App component, but it doesn't seem to work. The error message I receive is: Cannot set properties of undefined (setting 'hasOwnProperty') The error occu ...

The message "jest command not recognized" appears

My test file looks like this: (I am using create-react-app) import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Calculator'; import { getAction, getResult } from './actions/' ...

Jest is having difficulty locating a module while working with Next.js, resulting in

I am encountering some difficulties trying to make jest work in my nextjs application. Whenever I use the script "jest", the execution fails and I get the following result: FAIL __tests__/index.test.tsx ● Test suite failed to run ...

The attribute 'date' is not found within the class 'EmployeeScheduleExceptionModel', however, it is present in the parent class from which it inherits

I am working on a TypeScript project and I have defined my configurations in the tsconfig.json file as shown below: { "include": ["src*"], "compilerOptions": { "target": "es2021", &q ...

Experiencing an issue with hasClass when conducting jest testing on react components

I've recently started using Jest to test my React components, and this is my very first test. Here's the code snippet for my component: import React from 'react'; import PropTypes from 'prop-types'; import uuidv1 from 'uuid'; import withStyles from 'react ...

What is the best way to prevent jest.mock from being hoisted and only use it in a single jest unit test?

My goal is to create a mock import that will be used only in one specific jest unit test, but I am encountering some challenges. Below is the mock that I want to be restricted to just one test: jest.mock("@components/components-chat-dialog", () ...

The functionality of router.prefetch is not recognized, which is causing difficulties in verifying the submit function with React Testing Library

This is a test code for evaluating the functionality of a component. I am checking whether a form submit function is triggered or not. import React from 'react' import { render, screen, fireEvent } from '@testing-library/react' import '@testing-library/jes ...