Jest testing error Received: serializes to the same string
i try to play with jest to learn how to test my react application.
I have create a button that will only embed some element to keep the same style constantly.
Here is the code of my button :
export function searchBtn(triggerSearch) {
return (
<div className="d-flex justify-content-center my-3">
<input
type="submit"
className="btn btn-primary w-25"
value="Search"
onClick={(e) => {
e.preventDefault();
triggerSearch();
}}
></input>
</div>
);
}
Here is my test :
const { searchBtn } = require("./SearchBtn");
test("going to try the btn", () => {
function triggerSearch() {}
expect(searchBtn(triggerSearch)).toEqual(
<div className="d-flex justify-content-center my-3">
<input
type="submit"
className="btn btn-primary w-25"
value="Search"
onClick={(e) => {
e.preventDefault();
triggerSearch();
}}
></input>
</div>
);
});
I don't know why i always get this error :
Received: serializes to the same string
Thanks you in advance
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.
-
How can make an Automatic tests for Teradata
I am using SQL Teradata. My team and I are looking for a tool to automate testing. I'm not talking about a data quality test tool that I can do with a tool like Talend Data Quality.
I'm looking for a tool for the automation of tests for SQL Teradata.
Does someone have an idea?
thanks in advance,
Best regards, Slim
-
test cafe : removeRequestHook
So I use t.addRequestHooks to add a few requestMock
I have the impression that after the end on my test, the hook are still working.
Is there a way to remove all the requestMock in one line? or should I specify all the t.removeRequestHooks one by one?
-
How to test custom gradle plugin both with JUnit and manually in same sample project
My goal is to have this project setup:
example-gradle-plugin ├── build.gradle └── src ├── main │ ├── java │ │ └── com .... └── test ├── java │ └── example │ └── integrationtest │ │ # GradleRunner.create().withProjectDir(testProjectPath.toFile()).withPluginClasspath() │ └── SimpleProjectRegressionTest.java // └── resources └── simple │ # plugins { id "example-gradle-plugin" } ├── build.gradle │ # // includeBuild ../../../../example-gradle-plugin └── settings.gradle
So the folder src/test/resources/simple is both used from a JUnit test, but as well can be used to run gradle commands from the command line using the composite build approach.
So this should work
cd src/test/resources/simple gradle build
And this unit test should also work:
@Test public void testBuildSample() { final ClassLoader classLoader = ProjectSetupHelper.class.getClassLoader(); final Path sampleSourceRootPath = Paths.get(classLoader.getResource("simple").toURI()); final BuildResult result = GradleRunner.create() .withProjectDir(sampleSourceRootPath.toFile()) .withArguments("build") .withPluginClasspath() .build(); }
However, there is a caveat when running JUnit, the custom-plugin-sources are referred to in 2 different ways at the same time:
GradleRunner.create().withProjectDir(testProjectPath.toFile()).withPluginClasspath()
means to add project custom plugin files to the classpath for running the build during the unit test- In
src/test/resources/simple/settings.gradle
, theincludeBuild ...
command also refers to the custom plugin.
Is there an easier or cleaner way to achieve the above: Having a sample project with composite build that can be used from the commandline to verify local changes to the plugin, and using that sample project also in a unit test of the plugin?
Currently in the unit test I copy the sample folder to a temporary folder without settings.gradle to avoid such complications.
-
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!