Questions tagged [jestjs]

1

votes
1

answer
2.2k

Views

Problems with async code in Jest tests

I am having problem with getting the code into the beforeAll function finish and wait for the promise that resolves the storyLinks. The console log at the end of the snippet returns undefined but I need it to return the hrefs of the stories in my storybook. I cannot wrap this into an async function...
Ruxandra Anghel
1

votes
2

answer
233

Views

Jest/Enzyme test throws error when using hooks

I have a simple React component that uses the useState hook. This component works correctly in the application, but my Jest test gives me the error 'Hooks can only be called inside the body of a function component'. As far as I can tell, I am calling useState correctly and, again, it works fine wh...
Jim Ade
0

votes
1

answer
11

Views

TypeError: fetch.mockResponse is not a function

Running into the following error: TypeError: fetch.mockResponse is not a function Trying to test the following : getRequests = () => { let headersObj = { 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': this.props.services.Dashboard.subscription_key, } fetch(`${this.props.services.D...
usertestREACT
9

votes
1

answer
90

Views

Expecting an error with axios-mock-adapter

I am trying to test an axios get request with axios-mock-adapter, such that an error is thrown given a status that does not equal 200. However, when I execute the test (see api.test.js), I get the following message: Error: expect(function).toThrowError(undefined) Expected the function to throw an er...
Jimmy
10

votes
3

answer
145

Views

Jest: Testing window.location.reload

How do I write a test that makes sure that the method reloadFn does in fact reload the window? I found this resource but I am unclear on how to expect a window reload when writing a test when that window reload happens in a given function. Thanks for the help! const reloadFn = () => { window.locatio...
Jimmy
1

votes
2

answer
1.2k

Views

How to mock Push notification native module in React native jest tests?

When using the module react-native-push-notification, I had this error: FAIL __tests__/index.android.js ● Test suite failed to run Invariant Violation: Native module cannot be null. at invariant (node_modules/fbjs/lib/invariant.js:44:15) at new NativeEventEmitter (node_modules/react-native/Libra...
BigOther
1

votes
1

answer
2.4k

Views

Jest check if an elements attribute exists

I want to check with jest if the following svg path element contains the attribute d How do I use jest to search for specific attribute in an element?
Athif Shaffy
1

votes
1

answer
52

Views

JEST: select an HTML element through innerHTML

Folks, I have a React Component which on rendering has this HTML in it: 1 It's a pagination button, and I want to simulate a click on it. The hacky way to select this element was: const wrapper = Enzyme.mount(); wrapper.find('button.encryped-class__2TKgPzyme4') .first() .simulate('click'); I want to...
darth-coder
1

votes
2

answer
39

Views

How to test the args passed into document.body.appendChild with jest

I have a function that creates a script element and adds it to the body. It looks a bit like this: const s = document.createElement('script'); s.type = 'text/javascript'; s.src = 'https://myscript'; s.id = 'abc'; document.body.appendChild(s); I'm using testing using jest and am spying on the appendC...
Christopher Moore
4

votes
1

answer
163

Views

Jest - How to get coverage for mocked classes and implementations

I'm currently working on a project where I'm using Jest for unit testing and code coverage. Everything is working fine, except coverage for mocked classes/methods. I don't seem to get the desired coverage results. I've tried to find something in the Jest docs and searched online for an answer, but I...
1

votes
2

answer
52

Views

How to test wrapped component with enzyme?

My React components is wrapped with differents HOCs (i18next, graphql etc...), unfortunately I can't test my wrappedComponents with enzyme. What is your best practice to test your wrappedComponents? I do not wish to export wrapped and unwrapped components version, I would like to only export wrappe...
JonGiamp
0

votes
0

answer
7

Views

how to fix .babelrc configuration

I'm new when it comes to using babel with jest and i'm trying to run a snapshot test but when I try to run the test I get this error: ReferenceError: [BABEL] A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example: Invalid: `{ pr...
Ryan Christian
0

votes
0

answer
11

Views

Jest: setTimeout is being called too many times

I am testing a react component that uses setTimeout. The problem is that Jest is saying that setTimeout is called even though it clearly isn't. There is a setTimeout to remove something from the ui and another one to pause the timer when the mouse is hovering over the component. I tried adding a co...
RhinoBomb
1

votes
0

answer
1.2k

Views

Invariant Violation: A <Router> may have only one child element when testing (Jest + Enzyme)

I am starting to test a React + Redux + React-router application and I have been struggling with some basic tests. This is my component (company-view.js): import React, { Component } from 'react'; import { Redirect } from 'react-router-dom'; import {withCookies} from 'react-cookie'; import CompanySh...
Esteban Dib
1

votes
1

answer
96

Views

Preventing generation of Realm JS files when running Jest in Javascript?

I'm currently running React-Native(0.51) with Jest(21.2.1) and RealmJS(2.1.1). I've gotten them to play nicely where the RN app runs realm and my tests with jest work. The issue is that after running Jest, I end up with some artifacts, specifically: * default.realm * default.realm.lock * default.rea...
Zidail
1

votes
1

answer
286

Views

ReactJS/JestJS/Enzyme: How to test graphql() function used in compose()?

This is how I'm testing a very simple reactJS component with react-apollo via jestJS. I'm also using the coverage function of jest. But the coverage shows me, that I'm missing to test the line options: (props) => ({ in the graphql(). How should I do this correctly? Example.js import React, { Compone...
user3142695
1

votes
0

answer
385

Views

react-test-renderer error: TypeError: Cannot read property 'offsetWidth' of undefined

I am trying to test a component which renders the basic example of react-data-grid component (http://adazzle.github.io/react-data-grid/examples.html#/basic). The test code looks like this: import React from 'react'; import renderer from 'react-test-renderer'; import ExampleGrid from './ExampleGrid';...
vhorta
1

votes
0

answer
703

Views

Testing localStorage with Jest & React

I am using Jest to test my react app and I have a component that parses some state data from localStorage in the componentwillmount method and saves it to it's state. Like this: componentWillMount() { let keys = Object.keys(localStorage); let data = []; keys.map((key) => { if(Date.parse(key) && mome...
Brian McCall
1

votes
0

answer
388

Views

Set up map alias for WebPack and Jest

So I have this on my webpack.config.js resolve : { alias : { Actions : path.resolve(__dirname , 'src/actions/'), Components : path.resolve( __dirname , 'src/components/' ), Reducers : path.resolve( __dirname , 'src/reducers/' ), Sagas : path.resolve( __dirname , 'src/sagas/' ) } }, All is...
Jplus2
1

votes
1

answer
501

Views

reactjs / jest : unable to populate react-apollo component with data using MockedProvider?

I have written simple react-apollo component which uses graphql query to retrieve data from schema. On execution component works fine but, when I am writing test case for this component using jest framework together with MockedProvider(i.e. component of react-apollo/test-utils). I am unable to popul...
Pramod Jadhav
1

votes
0

answer
94

Views

DatePickerIOS doesn't like Jest mocked Date()

I'm setting up some Jest testing in my react-native project so i'm setting up snapshots for my components. One of them involves a DatePicker (specifically just time) so I needed to mock a consistent Date() for the snapshots to match. The docs for DatePickerIOS indicate it takes a Date object in the...
MattyK14
1

votes
1

answer
363

Views

jest for testing describe is not a function

I have made an app using react and redux, I have some components plus their containers and also an action and a reducer. I am writing a test for one of my containers using enzyme, chai and jest, when I try to run my test it gives the following error: Test suite failed to run TypeError: jest_1.descr...
S. N
1

votes
0

answer
155

Views

React handsonable test render issue- typeerror: cannot read property 'insertbefore' of null

I am writing a jest test for a React component that contains a HotTable from react-handsontable. However, I am getting the error 'TypeError: Cannot read property 'insertBefore' of null' when I render it in the test environment. Specificially my stateless functional component is of the form: import R...
digiplant
1

votes
0

answer
32

Views

Unable to add objects into Redux state during unit test

I'm attempting to add objects into my Redux store during a unit test to ensure my reducers and actions are working properly. It looks like the state that is showing up is the INITIAL_STATE from the reducer file. However, any time I add a new item into the reducer state, nothing happens. I'm presumin...
John Lippson
1

votes
1

answer
225

Views

How to test Nodejs request callback listener?

I use jest for unit test. my code is return new Promise((resolve, reject) => { let request = http.request(options, resp => { resp.setEncoding('utf-8'); let body = ''; resp.on('data', chunk => { body += chunk }); resp.on('error', error => { body += error; reject(body, resp); }); resp.on('end', () =>...
moslem
1

votes
0

answer
490

Views

Jest/React/Apollo "Cannot read property 'data' of undefined

I'm trying to get my head around testing. I've built a react/next/apollo app and I've attempted to write what I thought was a basic test but I can't get it to work. I get the following error: TypeError: Cannot read property 'data' of undefined 85 | constructor(props) { 86 | super(props) >...
Alex Foxleigh
1

votes
1

answer
1.1k

Views

Getting .then of undefined when trying to test a dispatch action function in React/Redux/Jest

component › toggleNotification actions › creates NOTIFICATION_REMOVE after successfull NOTIFICATION_ADD (error) TypeError: Cannot read property 'then' of undefined In my changePassword component 3 dispatch functions, and focusing on testing the toggleNotification. const mapDispatchToProps = disp...
Leon Gaban
1

votes
0

answer
577

Views

Jest unit test case for ternary operator

I need advice on how to write a jest unit test to cover the following lines of code: navbarHeight: (Platform.OS === 'ios') ? 64 : 54, statusBarHeight: (Platform.OS === 'ios') ? 16 : 0,
Taarun
1

votes
0

answer
437

Views

Jest mock a function within object

Trying the following : // Function Spies const onSubmitSpy = jest.fn().mockName('onSubmitSpy'); const onHistoryPushSpy = jest.fn().mockName('onPushSpy'); // Default Props const defaultProps = { signupUserMutation: onSubmitSpy, history: { push: onHistoryPushSpy } }; Then within my test this spy gets...
StevieB
1

votes
1

answer
45

Views

Enzyme/Jest — Writing TDD with DOM tree

Using shallow component, how do I test something like this that has DOM API (querySelector for instance) handleOnClick(e) { const { pageID } = this.props document.querySelector('form .event').name = '_eventID' + pageID document.querySelector('form').submit() e.preventDefault() } My test is breaking...
Alejandro
1

votes
1

answer
355

Views

Mocking node modules with Jest and @std/esm

I'm currently having an issue writing tests for a node application that uses @std/esm. I've setup a manual mock of a node module inside a __mocks__ directory and the following code shows a test for the file uses this mocked node module. (It's used in db.mjs) const loader = require('@std/esm')(module...
Luke Haas
1

votes
0

answer
129

Views

Why I need to IonicModule.forRoot(MyComponent) in order to use InfiniteScroll in component under tests

I'm using a stack with Angular 5, Ionic 3 and Jest to test a component in my App. Right now, the tests looks like this: describe('Feed Page', () => { let component: FeedPage; let fixture: ComponentFixture; beforeEach( async() => { TestBed.configureTestingModule({ declarations: [ FeedPage, VideoFrame...
Rodrigo Chaves
1

votes
0

answer
141

Views

How to integrate TestRail with Jest tests?

I'm running Jest integration tests on Jenkins and I want to integrate them with TestRail in order to automatically put test results to TestRail. In this way I will know easily how many tests are passed/failed? Does anyone tried that?
pensacola
1

votes
0

answer
904

Views

Mocking default exported function with Jest says it wasn't called but it was

[EDIT - POSSIBLE SOLUTION] So I realised that my componentWillMount is an async method since it is using an async fs wrapper to do fs operations. So I made the beforeEach function argument async and awaited on the Enzyme.shallow. This seems to have worked. It just came to me that if it's async maybe...
Andreas Andreou
1

votes
1

answer
397

Views

Jest tests with i18next and storybook

I use i18next in my component repo. Components are working fine, but I have problems with tests. I use i18next with hoc, when I export only component, tests are passing, but when I export it like export default translate ('components') (List); tests failed. I tried to make two exports, with hoc and...
lukasz-p
1

votes
0

answer
99

Views

Jest --findRelatedTests project structure/naming conventions

A similar question was asked back in May of last year but unfortunately didn't get any responses so I'd like to expand on it with some details of my own and hopefully gain some understanding of how --findRelatedTests works, because there doesn't seem to be any documentation that describes how it wor...
Andy
1

votes
0

answer
357

Views

Testing React Component Not Working with Material-UI

I am using jest-enzyme for testing and while using the mount method, I am unable to test the component inside material-ui's theme provider My test looks like this import React from 'react'; import PropTypes from 'prop-types'; import {mount} from 'enzyme'; // import API import * as API from '..//...
Marty
1

votes
0

answer
652

Views

Jest testing console log with Node

I'm attempting to test whether or not a function logs to the console. This is my current code being tested with Jest. const func = require('./func'); test('should print to the console', async () => { console.log = jest.fn(); await func('text.txt'); expect(console.log).toHaveBeenCalledWith(func); });...
James
1

votes
1

answer
500

Views

how to 'properly' write tests in typescript

i really love tdd, and want to pick up a new language, and have chosen typescript. Unfortunately i'm struggling to write tests the way i want to. say i am testing the following class: class Container { private numbers: number[]; constructor(){ this.numbers = []; } addNumber(numberToAdd: number) : v...
ocstat
0

votes
0

answer
3

Views

How to configure jest to run the different setup file during testing files in the different folder?

This is my structure: tests/unit ├── components │ ├── Form.spec.js │ ├── Hamburger.spec.js │ └── Table.spec.js ├── setup.js └── vuex └── mutations.spec.js Here is jest.config.js: module.exports = { verbose: true, moduleFileExtensions: ['js', 'jsx...
Billyyyyy3320

View additional questions