React - Enzyme Test - How to check class after simulate a click
I am new in React Enzyme testing. I'd like check class name after click button, and I am getting empty class for enzyme shallow wrapper.
Button.tsx
import React from 'react';
import style from './styles.module.scss';
export interface ButtonPropTypes {
title?: string;
}
const Button = ({ title }: ButtonPropTypes) => {
const [active, setActive] = useState(false);
return (
<div
className={cx(style.container, {
[style.active]: active,
})}
onClick={() => setActive(!active)}
>
{title}
</div>
);
}
export default Button;
Button.test.tsx
import React from 'react';
import { shallow, ShallowWrapper } from 'enzyme';
import Button from './index';
let wrapper: ShallowWrapper;
beforeEach(() => {
wrapper = shallow(<Button titie="Toggle Me"/>);
});
describe('<Button />', () => {
it('should be defined', () => {
expect(Button).toBeDefined();
});
it('should match snapshot', () => {
expect(wrapper).toMatchSnapshot();
});
it('should button toggle work', () => {
wrapper.find('div').first().simulate('click');
console.log(wrapper.debug()); // log looks like "<div class=""> ... </div>"
expect(wrapper.find('.active').length).toBe(0);
});
});
Please let me know how can I check the actual wrapper class has active characters when its status is active through the toggle action.
Cheers!
1 answer
-
answered 2021-01-15 15:09
James Lin
Make sure your project inject css classnames adding below config in jest.config.js file.
moduleNameMapper: { "^.+\\.(css|less|scss)$": "identity-obj-proxy" }
In your test file, you can check class name like below.
... it('should toggle action work', () =>. { wrapper.simulate('click'); expect(wrapper.find('.active').length).toBe(1); wrapper.simulate('click'); expect(wrapper.find('.active').length).toBe(0); }); ...
Good luck!
See also questions close to this topic
-
Auto import for react native is not working on vscode
I am developing a react native application, but no matter what I do the Auto import feature is not working for me on vscode. Feature I want (if you type , it'll automatically import the Text module from React) And this is what is happening now, which does not highlight any error for me My current problem screenshot
I have looked for some similar issues, but none was helpful to me. I tried fixing my eslint and also added jsconfig, and it did not work. Any advice would be very appreciated.
eslint.js:
module.exports = { extends: "airbnb", plugins: ["react", "react-native", "react-hooks"], parser: "babel-eslint", env: { jest: true, "react-native/react-native": true, }, rules: { "no-use-before-define": "off", "react/jsx-filename-extension": "off", "react/prop-types": "off", "comma-dangle": "off", "padded-blocks": "off", "arrow-body-style": "off", "react-hooks/exhaustive-deps": "warn", "react-native/no-unused-styles": 2, "react-native/split-platform-components": 2, "react-native/no-inline-styles": 2, "react-native/no-color-literals": 2, "react-native/no-raw-text": 2, "react-native/no-single-element-style-arrays": 2, }, globals: { fetch: false, }, // Indent with 4 spaces indent: ["error", 4], // Indent JSX with 4 spaces "react/jsx-indent": ["error", 4], // Indent props with 4 spaces "react/jsx-indent-props": ["error", 4], };
package.json:
{ "main": "node_modules/expo/AppEntry.js", "scripts": { "start": "expo start", "android": "expo start --android", "ios": "expo start --ios", "web": "expo start --web", "eject": "expo eject", "lint": "eslint *.js **/*.js src/**/*.js" }, "dependencies": { "expo": "~40.0.0", "expo-status-bar": "~1.0.3", "react": "16.13.1", "react-dom": "16.13.1", "react-native": "https://github.com/expo/react-native/archive/sdk-40.0.1.tar.gz", "react-native-web": "~0.13.12" }, "devDependencies": { "@babel/core": "~7.9.0", "babel-eslint": "^10.1.0", "eslint": "^7.20.0", "eslint-config-airbnb": "^18.2.1", "eslint-plugin-import": "^2.22.1", "eslint-plugin-jsx-a11y": "^6.4.1", "eslint-plugin-react": "^7.22.0", "eslint-plugin-react-hooks": "^4.2.0", "eslint-plugin-react-native": "^3.10.0" }, "private": true }
babel.config.js:
module.exports = function (api) { api.cache(true); return { presets: ["babel-preset-expo"], }; };
-
How to get state variables in redux action
import axios from "axios"; export const sessioninfor = () => { // I need to get state value and return it. } export const instance = axios.create({ baseURL: "https://aaaaaaaaaa.com/", timeout: 5000, headers: { "Content-Type": "application/json", authorization: `${encodeURIComponent(sessioninfor())}` }, }); export const AXIOS_REQUEST = async (url,inputdata,dispatch,loading) =>{ try{ if(loading){ dispatch({type : "HOMEPAGELOADIN",data : true}) } var Response = await instance.post( url , inputdata ); if(loading){ dispatch({type : "HOMEPAGELOADIN",data : false}) } if(Response.data){ return Response.data }else{ return {status : false,data : "error"} } }catch(e){ if(loading){ dispatch({type : "HOMEPAGELOADIN",data : false}) } return {status : false,data : "error"} } }
How can I get state variables in the sessioninfo function? I need to get the value and return it. What is the solution? If you know about this, please help me. Thank you.
-
How to get object data into the jsx?
I'm having a problem of not rendering the object data in the jsx. Here is the code.
import React from 'react'; import ReactDOM from 'react-dom'; import { useEffect,useState } from 'react'; const Mapper=(props)=>{ const currentCity=props.cities; console.log(currentCity); const mapped=currentCity.map(weatherDataMapper); const mappedObj=mapped[0]; console.log(mappedObj); console.log(mappedObj.city); return ( <ul> <li>yo wassup</li> {/* <li>{mappedObj.city}</li> */} </ul> ); } export default Mapper; function weatherDataMapper(data){ const general={ city:data.city.name, country:data.city.country, temperature:Math.round(data.list[0].main.temp), description:data.list[0].weather[0].description, humidity:data.list[0].main.humidity, icon:data.list[0].weather[0].icon, windSpeed:Math.round(data.list[0].wind.speed*3.6), feelsLike:Math.round(data.list[0].main.feels_like), } return general; }
i can get the mappedObj as a console output, but the 'mappedObj.city' couse an error "TypeError: can't access property "city", mappedObj is undefined". So how to solve this?? I'm a bit new to the react development btw.
-
Errro add component in Angular 11
When I try to add a component to app, appears this error but I don't know what is happen
My code
Error: src/app/product/product.component.ts:7:14 - error NG6002: Appears in the NgModule.imports of AppModule, but could not ble.imports of AppModule, but could not be resolved to an NgModule class. Is it missing an @NgModule annotation?
product.component.ts in app/product
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-product', templateUrl: './product.component.html', styleUrls: ['./product.component.scss'] }) export class ProductComponent implements OnInit { constructor() { } ngOnInit(): void { } }
app.module.ts
import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ProductComponent } from './product/product.component'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, FormsModule, ProductComponent ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
app.component.html
<app-product></app-product>
-
How can I pass an optional argument to an overloaded function in Typescript?
I have an overloaded function that I'm calling with an optional parameter. I'm having trouble figuring out how to get Typescript to find the errors correctly in this.
function inner<T>(innerArg: T) { function foo(): T; function foo(a: boolean): T & { a: boolean }; // function foo(a?: boolean): T | T & { a: boolean }; function foo(a?: boolean) { return a ? { ...innerArg, a } : innerArg; } return foo; } function wrapper<T>(outerArg: T, a?: boolean) { return inner(outerArg)(a); // Argument of type 'boolean | undefined' is not assignable to parameter of type 'boolean'. } const arg = { b: 1 } console.log(wrapper(arg).b); // 1 console.log(wrapper(arg, true).a); // true console.log(wrapper(arg, true).b); // 1 console.log(wrapper(arg).a); // should generate compilation error
If I uncomment that fourth line, adding an overload signature with an optional, the error in the wrapper goes away. However, then I get an error from the third to last line,
console.log(wrapper(arg, true).a);
which should be valid and which prints 'true'.
Is there a way of typing
inner
such that Typescript will correctly identify correct and incorrect usages ofinner
andwrapper
? -
Angular KeyValue Pipe not working on string/number enum, showing duplicates
How come this Angular keyvalue pipe is not working on enum below?
export enum test{ "Honda Accord" = 2 }; <div *ngFor="let testItem of test | keyvalue"> {{test.key}}
Its showing this in my Angular dropdown, both Key and Value twice. I only want to see Honda Accord text.
When I make 2 with a string quote, it will work. I want it working both ways.
export enum test { "Honda Accord" = "2" };
-
More than one test fails due to import after jest is torn down - Supertest Typescript and Express API
I am running into an issue where I am running multiple tests using
supertest
andjest
. When there is only one test running then it works just fine but the second one throws the following error:ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.
I tested this with two very simple tests:
describe("Default API", () => { describe("Default:", () => { it("should create a user in the DB", (done) => { request(app).get("/").expect(200, done); }); it("should create a user in the DB", (done) => { request(app).get("/").expect(200, done); }); }); });
They are the same but the second one throws the error. If I run only the first one there is no issue. This must be a setup issue Does anyone have advice. In my index.ts where I have the main express code I export app as follows:
export default app;
This is at the bottom of the index.ts file.
-
TypeError: Cannot read property 'getContext' of null
I have created a game using canvas API and now I am testing using Jest. But when running a test for a simple function it throws me this error. my script tag is at the end of the HTML and I also added this event listener to wait for the DOM document.addEventListener("DOMContentLoaded", init,false);
jest
PASS tests/sum.test.js FAIL tests/mod.test.js ● Test suite failed to run
TypeError: Cannot read property 'getContext' of null 20 | const empty = 0; 21 | const nextPieceCanvas = document.querySelector("canvas#nextPiece") as HTMLCanvasElement; > 22 | const NPctx = nextPieceCanvas.getContext("2d")! as CanvasRenderingContext2D; | ^ 23 | 24 | //Gameboard Canvas 25 | const canvas = document.querySelector("canvas#tetris") as HTMLCanvasElement; at Object.<anonymous> (src/ts/app.ts:22:31) at Object.<anonymous> (tests/mod.test.js:2:1)
Test Suites: 1 failed, 1 passed, 2 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.424 s Ran all test suites. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! tetris_ts@1.0.0 test:
jest
npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the tetris_ts@1.0.0 test script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above.npm ERR! A complete log of this run can be found in: npm ERR! /home/alex/.npm/_logs/2021-02-26T22_46_02_771Z-debug.log
enter code here
-
nestjs unit test createTestingModule Dependency Injection
I hope you can help me out. I am using Nx with latest angular/nestjs (date: February, 26)
... "@nestjs/common": "^7.0.0", "@nestjs/config": "^0.6.3", "@nestjs/core": "^7.0.0", "@nestjs/platform-express": "^7.0.0", "@nestjs/platform-socket.io": "^7.6.7", "@nestjs/websockets": "^7.6.7", "jest": "26.2.2", "@nrwl/jest": "11.4.0", ...
I cannot get my unit test running using NestJS with Jest I want to test following service:
@Injectable() export class CoreApiService { logger = new Logger('CoreApiService'); apiEndpoint; constructor(private httpService: HttpService, configService: ConfigService) { this.apiEndpoint = configService.get('API_SERVICE_ENDPOINT'); } }
and I get following error:
TypeError: Cannot read property 'get' of undefined
so it seems that the ConfigService (and also httpService) is always undefined.
when logging httpService and ConfigService, it will always be undefined. Even when I try to instantiate new Instances like
new CoreApiService(new HttpService(), new ConfigService())
I've even tried things likenew CoreApiService({} as any, {get: (...params} => {return 'foo'})
in the test itselfit will always be the same error mentioned above.
The test file:
import { Test, TestingModule } from '@nestjs/testing'; import { CoreApiService } from './core-api.service'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { HttpModule } from '@nestjs/common'; class ConfigServiceMock { get(key: string): string { switch (key) { case 'API_SERVICE_ENDPOINT': return ''; } } } describe('CoreApiService', () => { let module: TestingModule; let service: CoreApiService; beforeEach(async () => { module = await Test.createTestingModule({ imports: [HttpModule, ConfigModule], providers: [ CoreApiService, { provide: ConfigService, useClass: ConfigServiceMock }, ], }).compile(); service = module.get<CoreApiService>(CoreApiService); }); it('should be defined', () => { expect(service).toBeDefined(); }); });
I've even tried:
.overrideProvider(ConfigService).useClass(ConfigServiceMock)
Thank you in advance!
-
How to write test cases for getter and setter in react?
get ipVersion (){ return this.query.ipVersion } set ipVersion ( newIPVersion ){ this.updateQuery ( { ...this.query, ipVersion : newIPVersion, parameters : { ...this.query.parameters, isValid : hostInputValidator ( this.query.parameters.value ) } }) }
I have
class Query
where I have to set and get different values so how to write test cases for getter and setter??? I am new toReact
so please can someone help me out???const query={ ipVersion: 'ipv4', network: 'internet', router: 'any', command: 'ping', parameters: { id: 'string', value: 'any', isValid: true } }
these all are the values to be
set
andget
-
Enzyme with react 17.0.1
I'm tryng to install this enzyme adapter for react17 and during the install throw me this error:
$ npm install --save-dev @wojtekmaj/enzyme-adapter-react-17 npm WARN ERESOLVE overriding peer dependency npm WARN Found: react@17.0.1 npm WARN node_modules/react npm WARN peer react@"^0.14.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" from mini-create-react-context@0.4.1npm WARN node_modules/mini-create-react-context npm WARN mini-create-react-context@"^0.4.0" from react-router@5.2.0 npm WARN node_modules/react-router npm WARN 4 more (react-router, react-router-dom, the root project, @wojtekmaj/enzyme-adapter-react-17) npm WARN npm WARN Could not resolve dependency: npm WARN peer react@"0.13.x || 0.14.x || ^15.0.0-0 || ^16.0.0-0" from enzyme-adapter-utils@1.14.0 npm ERR! peer react@"^0.14.0 || ^15.0.0 || ^16.0.0 || ^17.0.0" from mini-create-react-context@0.4.1npm ERR! node_modules/mini-create-react-context npm ERR! mini-create-react-context@"^0.4.0" from react-router@5.2.0 npm ERR! node_modules/react-router npm ERR! react-router@"5.2.0" from react-router-dom@5.2.0 npm ERR! node_modules/react-router-dom npm ERR! react-router-dom@"^5.2.0" from the root project npm ERR! peer react@">=15" from react-router@5.2.0 npm ERR! node_modules/react-router npm ERR! react-router@"5.2.0" from react-router-dom@5.2.0npm ERR! node_modules/react-router-dom npm ERR! react-router-dom@"^5.2.0" from the root project npm ERR! 3 more (react-router-dom, the root project, @wojtekmaj/enzyme-adapter-react-17) npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer react@"^0.14 || ^15.0.0 || ^16.0.0-alpha" from airbnb-prop-types@2.16.0 npm ERR! node_modules/enzyme-adapter-utils/node_modules/airbnb-prop-types npm ERR! airbnb-prop-types@"^2.16.0" from enzyme-adapter-utils@1.14.0 npm ERR! node_modules/enzyme-adapter-utils npm ERR! enzyme-adapter-utils@"^1.14.0" from @wojtekmaj/enzyme-adapter-react-17@0.4.1 npm ERR! node_modules/@wojtekmaj/enzyme-adapter-react-17 npm ERR! dev @wojtekmaj/enzyme-adapter-react-17@"*" from the root project npm ERR! npm ERR! Fix the upstream dependency conflict, or retry npm ERR! this command with --force, or --legacy-peer-deps npm ERR! to accept an incorrect (and potentially broken) dependency resolution. npm ERR! npm ERR! See C:\Users\dittl\AppData\Local\npm-cache\eresolve-report.txt for a full report.
It's this a problem beacause I'm using react 17.0.1? Because in the past I work with the enzyme adapter in react 17 and works perfect.
-
Setting initial use state values for testing returns an object
Looking to set the initial state for my useState hooks for testing.
Looking at the various examples here and other blogs, the closest I have
come is with the following implementation. But it ends up returning the value
as an object instead of setting the actual state values.The useState implementation I am trying to initialise.
const [names, setNames] = React.useState([]); const [count, setCount] = React.useState(0); const selectCard = (id) => { if (names.includes(id)) { // it breaks at this .includes call during test // do something }
Error thrown.
names.includes is not a function.
It breaks cos names, instead of being the initialised as an array, it ends up coming in as
an object. Is there something wrong in the way I am mocking cos I was expecting the names to be an array
and count to hold the value 3 instead.The following object is the wrong value from names in current mocking. Coming in as an object instead of individually assigning values to each useState as follows.
After mocking, this ends up being the values of names.
{ names: ['Jack], count: 3 }
The test case
const setHookState = (newState) => jest.fn().mockImplementation(() => [ newState, () => {}, ]); it('should work ....', () => { React.useState = setHookState({ names: [], count: 3, }); const rendered = render(); // some tests })