How to test components that depend on NODE_ENV with Jest
I got this component I want to test
export const ResponsiveChartContainer = ({ children, height }: Props): React.ReactElement => {
return process.env.NODE_ENV === 'test' ? (
children
) : (
<ResponsiveContainer minHeight={height}>{children}</ResponsiveContainer>
);
};
It relies on NODE_ENV because ResponsiveContainer does not render any children on testing environment.If I put the ResponsiveContainer on the parent container, the graph does not show at all. So removing the ResponsiveContainer from the component is not an option. How can I test it?
I have tried setting NODE_ENV on the test itself but typescript complains it is a read-only variable.
See also questions close to this topic
-
Unable to catch and log the error from axios request
I'm validating user input and result in express and am returning 422 if the input is invalid and a 400 if result is empty. The problem is that I can't log the response object when an error occurs.
Nodejs:
if (q === '' || q.length < 3 || q.length > 150) { console.log('invalid query'); return res.sendStatus(422).send('Search not found'); } else { try { // Fetch redis data const data = await GET_ASYNC('data'); // stuff here // Result Validation if (!Array.isArray(data) || !data.length) { res.status(400).send('Search not found'); } else { // do stuff res.status(200).send(data); } } catch (err) { console.error(err); res.sendStatus(500); // Server error }
Now my react code:
const searchDb = useCallback(async() => { const CancelToken = axios.CancelToken; const source = CancelToken.source(); try { axios.get(`/api/bestProduct?q=${searchValue}`, { cancelToken: source.token }) .then(res => { console.log(res) // nothing shows up const data = res.data; setData(data) }); } catch (err) { if (axios.isCancel(err)) { console.log(err.response); // nothing shows up } else { console.log('hello??') // nothing return setError(`There's been a problem on our end.`) } } }, [])
I've looked at other solution and tried to log the res and res.status but nothing shows up. This is what my console looks like during the error:
-
Dynamic object keys... Cannot create property on string
I'm trying to make an input automatically store its value in an object. The key should be the input's id. Ex: {screen1_input1: 'whatever'}. The first character does that. The second character crashes with "TypeError: Cannot create property on string". I think I see what's happening but I don't know how to fix it.
import { useState } from 'react' function Demo() { const [contentData, setContentData] = useState({}) const onChange = (e) => { let oldData = contentData setContentData(oldData[e.target.id] = e.target.value) console.log('*') } const Screen1 = () => { return ( <> <input type="text" id="screen1_input1" onChange={onChange} /> </> ) } return ( <> <h2 className="Demo"> {Screen1()} </h2> </> ) } export default Demo
-
How can I extract a nested array of objects and put them in the core array?
I am working on a functionality where I need to group some items and also ungroup them.
Some days ago I asked this question: How can I group specific items within an object in the same array and delete them from the core array? where a couple of people helped me solving the grouping part. But it is very related to this question.
What I need to do now, is to ungroup the items with the exact same requirement: ungroup the
checked === true
group and put the items back from where they came from and remove all duplicates.Here is a reproducible demo with both functionalities: https://codesandbox.io/s/ts-react-grouping-forked-rmwhr?file=/src/App.tsx
And here the relevante piece of code:
const handleUngroupingQuestions = (): void => { const questionAddedCopy: VariableConfig[] = [...questionAdded] const filteredByChecked: VariableConfig[] = questionAddedCopy.filter((q: VariableConfig) => isCheck.includes(q.id)) if (isCheck.length) { setCheck([]) const extractGroup = (i: number): VariableConfig[] => filteredByChecked[i].questionGroup const addChecked = (q: VariableConfig): VariableConfig => ({ ...q, questionGroup: [] }) // @TODO // Remove this when we have a proper data structure clearVariable() const nestChecked = (qs: VariableConfig[], found = false) => qs.flatMap((q: VariableConfig, i: number) => { if (filteredByChecked.includes(q)) { if (found) { return [] } else { found = true return [...[addChecked(q)], ...extractGroup(i)] } } else { return [q] } }) const getNew = [...nestChecked(questionAdded)] console.log({ getNew: JSON.stringify(getNew, null, 2) }) addQuestion(getNew.filter((g, i, a) => a.indexOf(g) === i)) } }
For some reason right now I am getting an error:
Cannot read property 'questionGroup' of undefined
Something is happening with an index.
So what I need is to group all of the items with the checked property being true. Then click on
ungroup
and bring the items back to its original position and deleting the current group. I must be able to do that even when there are multiple groups of questions.What am I missing?
-
Property 'forEach' does not exist on type 'string | string[]'
I have this code
@Where( ['owner', 'Manager', 'Email', 'productEmail', 'Region'], (keys: string[], values: unknown) => { const query = {}; keys.forEach((k: string) => { } )
when I enabled strict rule for type checks it's complaining
Argument of type '(keys: string[], values: unknown) => {}' is not assignable to parameter of type '(key: string | string[], values: unknown) => unknown'. Types of parameters 'keys' and 'key' are incompatible. Type 'string | string[]' is not assignable to type 'string[]'. Type 'string' is not assignable to type 'string[]'.ts
when i change keys type to
(keys: string | string[], values: unknown) =>
I am getting another error
Property 'forEach' does not exist on type 'string | string[]'. Property 'forEach' does not exist on type 'string'.ts
Can someone have any idea on how to resolve this issue.
-
TypeError: Cannot read property 'https' of undefined
I have a nuxt app built with firebase and vue. Everytime I run my emulator, it would not proceed because of this error:
TypeError: Cannot Find Property 'https' of undefined.
I am having problems with myhttps
in my index.ts file. It says that they cannot find this property. I already imported everything from firebase-functions but it still doesnt work.This was added in the first line:
const { functions } = require("firebase-functions");
I also have this line of code:
exports.nuxtssr = functions.https.onRequest(app);
I found some solutions in Stack Overflow and tried these solutions, but it still would not work: How to import firebase-functions and firebase-admin in ES6 syntax for transpiling with Babel for Node 10
-
Jest mock middleware response
I am trying to mock a middleware response, and i am trying to use
jest.spyOn()
but can't seem to get it workingMy controller.ts has the following
import someMiddleware from '../someMiddleware; .... .... this.route.post('/getData', someMiddleware, setValue)
In someMiddlware.ts
//making a fetch call based on data in req.body ..... const data = await fetchData(url, data) next() .....
In my test file controller.test.ts
describe('Test Data', () => { beforeEach(() => { someMiddlewareSpyOn = jest.spyOn(meddelware, "someMiddleware"); }); afterEach(() => { jest.resetModules(); jest.resetAllMocks(); }); it('response status should be a 200', async () => { someMiddlewareSpyOn.mockResolvedValue({data:[].....}); const res = await request(app.getServer()) .post('/getData'); expect(res.status).toBe(200); }) });
The above does not work, looking for assistance on how to do this.
-
Testing Controller and Service in Jest
I'm fairly new to Jest and have been trying (with no luck) to figure out how to write tests for my controller. I'm not sure how to write the test as it calls another function. It would be great if I could get pointed in the right direction at least. Thanks in advance.
controller.ts
import * as Services from './services'; export async function GetCountriesList(req: Request, res: Response): Promise<void> { const response = await Services.GetCountriesList(); res.status(response.code).json({ status: response.status, message: response.message, count: response.count, data: response.data }); }
service.ts
import db from '../../modules/db'; import { DBGenericDataResponse } from '../../types/models'; export async function GetCountriesList(): Promise<DBGenericDataResponse> { const lQuery = 'somquery'; const responseMessage: DBGenericDataResponse = { code: 200, status: 'ok', message: '', count: 0, data: [], error: '' }; try { const dbResult = await db.query<any>(lQuery); responseMessage.message = 'Countries returned'; responseMessage.count = dbResult.rows.length; responseMessage.data = dbResult.rows; } catch (err) { responseMessage.code = 400; responseMessage.status = 'error'; responseMessage.message = 'Error retrieving Countries List'; responseMessage.error = err; } return responseMessage; }
-
Warning: <TEXT /> is using incorrect casing
console.error node_modules/react-dom/cjs/react-dom.development.js
Warning:
<TEXT />
is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements.I have the issue with Jest and react-pdf
In the component where I'm using the react-pdf components this is written as:
<Text>
, but when performing the test it's appearing as<TEXT>
My component:
const HeaderPDF: React.FC<Props> = (props: Props) => { return ( <View style={styles.headerContainer} fixed> <View style={styles.headerTop}> <Text style={styles.textBoldTopHeader}> "Some text" </Text> <View style={styles.headerTopInputContainer}> <View style={styles.headerTopInputTextContainer}> <Text style={styles.textInputTopHeader}>Route</Text> </View> <View style={styles.inputSmall} /> </View> </View> </View> ); };
The test:
import React from 'react'; import { render } from 'tests/support/customRender'; import HeaderPDF from ../../HeaderPDF'; describe('HeaderPDF', () => { it('Renders a HeaderPDF component successfully', () => { const { container } = render( <HeaderPDF someProps /> ); expect(container).toMatchSnapshot(); }); });