XMLHttpRequest testing in Jest

The jest api has changed a bit. This is what I use. It doesn’t do anything but it’s enough to render my components. const xhrMockClass = () => ({ open : jest.fn(), send : jest.fn(), setRequestHeader: jest.fn() }) window.XMLHttpRequest = jest.fn().mockImplementation(xhrMockClass) and in the test file: import ‘../../__mock__/xhr-mock.js’

jest: Test suite failed to run, SyntaxError: Unexpected token import

Jest sets the env variable to test, so I had to add my presets to the env setting in .babelrc: { “plugins”: [“syntax-dynamic-import”, “transform-runtime”], “presets”: [ [ “es2015”, { “modules”: false } ], “react”, “stage-0” ], “env”: { “start”: { “presets”: [ “react-hmre” ] }, “test”: { “presets”: [“es2015”, “react”, “stage-0”] } } }

How to test Async Storage with Jest?

For everyone who sees this question in > 2019: Since Nov 2020, AsyncStorage was renamed back to @react-native-async-storage/async-storage”, which causes this warning to appear if you’re importing it from react-native: Warning: Async Storage has been extracted from react-native core and will be removed in a future release. The new module includes its own mock, so … Read more

Using Jest to test a Link from react-router v4

You can wrap your component in the test with the StaticRouter to get the router context into your component: import React from ‘react’; import renderer from ‘react-test-renderer’; import { Link } from ‘react-router-dom’; import { StaticRouter } from ‘react-router’ test(‘Link matches snapshot’, () => { const component = renderer.create( <StaticRouter location=”someLocation” context={context}> <Link to=”#” /> … Read more

How to mock React component methods with jest and enzyme

The method can be mocked in this way: it(‘handleNameInput’, () => { let wrapper = shallow(<MyComponent/>); wrapper.instance().searchDish = jest.fn(); wrapper.update(); wrapper.instance().handleNameInput(‘BoB’); expect(wrapper.instance().searchDish).toBeCalledWith(‘BoB’); }) You also need to call .update on the wrapper of the tested component in order to register the mock function properly. The syntax error was coming from the wrong assingment (you need … Read more

Jest spyOn function called

You were almost done without any changes besides how you spyOn. When you use the spy, you have two options: spyOn the App.prototype, or component component.instance(). const spy = jest.spyOn(Class.prototype, “method”) The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important. const spy = jest.spyOn(App.prototype, “myClickFn”); const … Read more