running mount() in react native Not Possible? - javascript

This post follows up with my previous question:
previous question
I have come across a test which requires me to run mount in react native. I have gone through the documentation in jest and have found that before running the test suite you specifically need to setup a test environment capable of running jsdom for mount to work:
The link to docs is:
testEnvironment
Because of it's horrible documentation. I can't figure out how to create the customEnvironment class and what after that? what do I do with the global object? How to use it in my test file which currently looks like:
describe('Estimate', () => {
test('Estimate component Exists', () => {
const onPressFunction = jest.fn()
const obj = shallow(
<Estimate onPress={onPressFunction} />
)
expect(obj.find('TextInput').exists()).toBe(true)
})
test('Estimate returns value on button press', () => {
const onPressFunction = jest.fn()
const obj = shallow(
<Estimate onPress={onPressFunction} />
)
obj.find('TextInput').first().simulate('keypress', { key: '1' })
obj.find('Button').first().props().onPress()
expect(onPressFunction.toHaveBeenCalledWith('1'))
})
})

I just made it work had to import three packages from npm:
jsdom
react-native-mock-renderer
jest-environment-jsdom
Also my setup.mjs file looks like:
// #note can't import shallow or ShallowWrapper specifically
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
// eslint-disable-next-line
import { format } from 'prettier'
Enzyme.configure({ adapter: new Adapter() })
// Make Enzyme functions available in all test files without importing
global.shallow = Enzyme.shallow
Enzyme.ShallowWrapper.prototype.jsx = function jsx () {
const placeholder = '{ something: null }'
const obj = this.debug({ ignoreProps: false, verbose: true }).replace(/{\.\.\.}/g, placeholder)
return format(obj, {
parser: 'babylon',
filepath: 'test/setup.mjs',
trailingComma: 'all',
semi: false,
arrowParens: 'always',
})
.replace(new RegExp(placeholder, 'g'), '{...}')
.replace(';<', '<')
}
// the html function just throws errors so it's just reset to be the jsx function
Enzyme.ShallowWrapper.prototype.html = Enzyme.ShallowWrapper.prototype.jsx
jest.mock('react-native-device-info', () => {
return {
getDeviceLocale: () => 'en',
getDeviceCountry: () => 'US',
}
})
jest.mock('react-native-custom-tabs', () => ({
CustomTabs: {
openURL: jest.fn(),
},
}))
jest.mock('react-native-safari-view', () => ({
isAvailable: jest.fn(),
show: jest.fn(),
}))
const { JSDOM } = require('jsdom')
const jsdom = new JSDOM()
const { window } = jsdom
function copyProps (src, target) {
const props = Object.getOwnPropertyNames(src)
.filter((prop) => typeof target[prop] === 'undefined')
.map((prop) => Object.getOwnPropertyDescriptor(src, prop))
Object.defineProperties(target, props)
}
global.window = window
global.document = window.document
global.navigator = {
userAgent: 'node.js',
}
copyProps(window, global)
Enzyme.configure({ adapter: new Adapter() })
// Ignore React Web errors when using React Native
// allow other errors to propagate if they're relevant
const suppressedErrors = /(React does not recognize the.*prop on a DOM element|Unknown event handler property|is using uppercase HTML|Received `true` for a non-boolean attribute `accessible`|The tag.*is unrecognized in this browser)/
const realConsoleError = console.error
console.error = (message) => {
if (message.match(suppressedErrors)) {
return
}
realConsoleError(message)
}
require('react-native-mock-render/mock')
Test looks like:
test('Estimate returns value on button press', () => {
const onPressFunction = jest.fn()
const tree = mount(
<Estimate onPress={onPressFunction} />
)
console.log(tree.children().first().html())
})
Works like a charm!

Related

Override a mocked consumer body for certain tests

I have the following test which works.
import React from 'react';
import { mount } from 'enzyme';
import MyLogin from '../../src/components/MyLogin';
const mockContent = {
data: {
config: {
myImage: 'mock_image',
},
},
};
jest.mock('../../src/utils/config', () => ({
Consumer: ({ children }) => children(mockContent),
}));
describe('Component Test', () => {
beforeEach(() => {
jest.resetModules();
});
const render = () => mount(
<MyLogin />
);
it('should render the component', () => {
const renderedModule = render();
expect(renderedModule).toMatchSnapshot();
});
});
But I wish to add another test where the values inside the mockContent changes.
I have added a isValid key.
Thus tried the following where I am trying to over ride mock only for this test.
But this doesn't work. No errors. No effect from this mock.
If I had added this new key isValid at the above mock outside the test, it does have the desired effect. (Can't do that of course cos that would affect my other tests)
Could I get some help with this pls.
describe('Component Test', () => {
// other tests
it('my new test', () => {
// attempting to override the above mock.
const myNewMockContent = {
data: {
config: {
myImage: 'mock_image_2',
isValid: true,
},
},
};
jest.mock('../../src/utils/config', () => ({
Consumer: ({ children }) => children(myNewMockContent),
}));
const renderedModule = render();
expect(renderedModule).toMatchSnapshot();
});
});

Implementing createMatchMedia() for material-ui. I'm using a material ui hidden component to hide buttons while I'm trying to test them

I'm using React-testing-library getByText to find a button that's hidden by a material ui component called Hidden. Since RTL won't find it, Material ui has an implementation of it here https://material-ui.com/components/use-media-query/#testing. But I can't figure out how to implement it to simply to find a button. The button is located once I remove Hidden, I am just not sure how to use their createMatchMedia() for a query within my test.
The Hidden component hides my button at 959px and down .
import React from "react"
import { render } from '../../../../test/test-utils'
import Collections from "./Collections"
import userEvent from '#testing-library/user-event'
import mediaQuery from 'css-mediaquery'
function createMatchMedia(width: any) {
return (query: string): any => ({
matches: mediaQuery.match(query, { width }),
addListener: () => {},
removeListener: () => {},
});
}
type CollectionsProps = React.ComponentProps<typeof Collections>
const baseProps: CollectionsProps = {
setValue: () => {},
setSelectedIndex: () => {},
pageStyle: {},
pageAnimations: {transition : {}, variants: {}},
motions: {animate:'', initial: '', exit: ''},
jumpTo: (jumpingTarget: string | number | Element): void => {}
}
const renderUI = (props: Partial<CollectionsProps>) =>
render(<Collections {...baseProps} {...props} />, {})
describe('When a filter is clicked', () => {
beforeAll( () => {
window.matchMedia = createMatchMedia(window.innerWidth)
})
let { getByText } = renderUI({})
test('items shown are only related to the picked Category', () => {
userEvent.click(getByText(/Team Colors/))
})
})
RTL is not the problem here. The problem is in jsdom which doesn't have an implementation of matchMedia(). Jest uses jsdom internally and without an existing matchMedia() no media query will match in Material UI's Hidden API.
You may solve this by first installing NPM packages css-mediaquery and #types/css-mediaquery.
Then create a mock for matchMedia like so:
// matchMedia.mock.ts
export const createMatchMedia = (width: number) => (query: string): MediaQueryList => ({
matches: mediaQuery.match(query, { width }),
media: query,
onchange: null,
addListener: () => jest.fn(),
removeListener: () => jest.fn(),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn()
});
window.matchMedia = createMatchMedia(window.innerWidth);
export default {};
Import the mock file above in setupTest.ts (your Jest test setup file) like so:
// setupTests.ts
import './__mocks__/matchMedia.mock';
...
Write your test as you normally would. No need to use the beforeAll() to create a new window.matchMedia. The mock file takes care of that for you.

useHistory hook inside useEffect create infinite loop in jest tests

I'm very annoyed since the morning cause I can't test my custom hooks without this infinite loop.
My custom hook look like :
useGetObj1.tsx
export function useGetObj1(): [
{ obj1: IObj1 | null; obj2: IObj2 | null } | null,
Function
] {
const User = useSelector((state: IStoreState) => state.User);
const history: History = useHistory();
const resState = useState<{ obj1: IObj1 | null; obj2: IObj2 | null } | null>(null);
const setState = resState[1];
useEffect(() => {
async function setStateValue() {
let tmp = null;
const res = await ParseVerifObj1(User, history.location.pathname);
if (typeof res !== "number") {
res
? (tmp = {
obj1: res.obj1,
obj2: res.obj2,
})
: (tmp = { obj1: null, obj2: null });
setState(tmp);
} else if (res === -1) history.push("/HomePage");
}
setStateValue();
}, [history.location.pathname, User, setState]);
return resState;
}
My test looks like :
useGetObj1.spec.js
jest.mock("axios");
jest.mock("react-router-dom", () => ({
useHistory: () => ({
push: jest.fn(),
location: {
pathname: "/path/web",
},
}),
}));
// make setup-jest file and put it later
import "axios";
import "babel-polyfill";
//
import React from "react";
import { mount } from "enzyme";
import { Provider } from "react-redux";
// import ParseVerifObj1 to mock it
import * as ParseVerifObj1 from "../path";
// custom hook tested here
import { useGetObj1 } from "../path";
import configureStore from "redux-mock-store";
// act to handle the Promise and the re-render of the renderHook
import { act } from "react-dom/test-utils";
// Utils Initial store
import { initialStore } from "../path";
import routeData from "react-router";
const mockStore = configureStore();
const mockLocation = {
pathname: "/",
hash: "",
search: "",
state: "",
};
jest.spyOn(routeData, "useLocation").mockReturnValue(mockLocation);
describe("useGetObj1.spec.js", () => {
let store;
beforeEach(() => {
store = mockStore(initialStore);
jest.clearAllMocks();
});
let results;
let wrapper;
const renderHook = (hook) => {
function HookWrapper() {
results = hook();
return null;
}
wrapper = mount(
<Provider store={store}>
<HookWrapper />
</Provider>
);
return results;
};
describe("Testing the custom hook : useGetObj1", () => {
it("useGetLesson is ran", async () => {
await act(async () => renderHook(useGetObj1));
expect(wrapper).toBeTruthy();
});
it("Testing the output adress values get from the ParseVerifObj1 function", async () => {
const spy = jest.spyOn(ParseVerifObj1, "ParseVerifObj1");
const lesson = Symbol("Obj1");
const session = Symbol("Obj2");
spy.mockReturnValue({
Obj1,
Obj2,
});
await act(async () => renderHook(useGetObj1));
expect(spy).toHaveBeenCalledWith(
initialStore.User,
"/path/web"
);
expect(spy).toHaveBeenCalled();
expect(results[0].Obj1).toBe(Obj1);
expect(results[0].Obj2).toBe(Obj2);
expect(results[1]).toBeInstanceOf(Function);
});
I know it's not a good thing to put history in the useEffect's dependencies but I got a warning like
Line 39:6: React Hook useEffect has a missing dependency: 'history'. Either includes it or remove the dependency array
and I tried a lot of different implementation but no one fixed the problem and compile without a warning
thx for helping :)
_Solution
The solution for me was to use useRef to avoid the dependencies requirement like this :
const history: History = useRef(useHistory());
with the ref you do not need anymore to put it as a dependency

How to mock an exported const in jest

I have a file that relies on an exported const variable. This variable is set to true but if ever needed can be set to false manually to prevent some behavior if downstream services request it.
I am not sure how to mock a const variable in Jest so that I can change it's value for testing the true and false conditions.
Example:
//constants module
export const ENABLED = true;
//allowThrough module
import { ENABLED } from './constants';
export function allowThrough(data) {
return (data && ENABLED === true)
}
// jest test
import { allowThrough } from './allowThrough';
import { ENABLED } from './constants';
describe('allowThrough', () => {
test('success', () => {
expect(ENABLED).toBE(true);
expect(allowThrough({value: 1})).toBe(true);
});
test('fail, ENABLED === false', () => {
//how do I override the value of ENABLED here?
expect(ENABLED).toBe(false) // won't work because enabled is a const
expect(allowThrough({value: 1})).toBe(true); //fails because ENABLED is still true
});
});
This example will work if you compile ES6 modules syntax into ES5, because in the end, all module exports belong to the same object, which can be modified.
import { allowThrough } from './allowThrough';
import { ENABLED } from './constants';
import * as constants from './constants';
describe('allowThrough', () => {
test('success', () => {
constants.ENABLED = true;
expect(ENABLED).toBe(true);
expect(allowThrough({ value: 1 })).toBe(true);
});
test('fail, ENABLED === false', () => {
constants.ENABLED = false;
expect(ENABLED).toBe(false);
expect(allowThrough({ value: 1 })).toBe(false);
});
});
Alternatively, you can switch to raw commonjs require function, and do it like this with the help of jest.mock(...):
const mockTrue = { ENABLED: true };
const mockFalse = { ENABLED: false };
describe('allowThrough', () => {
beforeEach(() => {
jest.resetModules();
});
test('success', () => {
jest.mock('./constants', () => mockTrue)
const { ENABLED } = require('./constants');
const { allowThrough } = require('./allowThrough');
expect(ENABLED).toBe(true);
expect(allowThrough({ value: 1 })).toBe(true);
});
test('fail, ENABLED === false', () => {
jest.mock('./constants', () => mockFalse)
const { ENABLED } = require('./constants');
const { allowThrough } = require('./allowThrough');
expect(ENABLED).toBe(false);
expect(allowThrough({ value: 1 })).toBe(false);
});
});
Unfortunately none of the posted solutions worked for me or to be more precise some did work but threw linting, TypeScript or compilation errors, so I will post my solution that both works for me and is compliant with current coding standards:
// constants.ts
// configuration file with defined constant(s)
export const someConstantValue = true;
// module.ts
// this module uses the defined constants
import { someConstantValue } from './constants';
export const someCheck = () => someConstantValue ? 'true' : 'false';
// module.test.ts
// this is the test file for module.ts
import { someCheck } from './module';
// Jest specifies that the variable must start with `mock`
const mockSomeConstantValueGetter = jest.fn();
jest.mock('./constants', () => ({
get someConstantValue() {
return mockSomeConstantValueGetter();
},
}));
describe('someCheck', () => {
it('returns "true" if someConstantValue is true', () => {
mockSomeConstantValueGetter.mockReturnValue(true);
expect(someCheck()).toEqual('true');
});
it('returns "false" if someConstantValue is false', () => {
mockSomeConstantValueGetter.mockReturnValue(false);
expect(someCheck()).toEqual('false');
});
});
There is another way to do it in ES6+ and jest 22.1.0+ thanks to getters and spyOn.
By default, you cannot spy on primitive types like boolean or number. You can though replace an imported file with your own mock. A getter method still acts like a primitive member but allows us to spy on it. Having a spy on our target member you can basically do with it whatever you want, just like with a jest.fn() mock.
Below an example
// foo.js
export const foo = true; // could be expression as well
// subject.js
import { foo } from './foo'
export default () => foo
// subject.spec.js
import subject from './subject'
jest.mock('./foo', () => ({
get foo () {
return true // set some default value
}
}))
describe('subject', () => {
const mySpy = jest.spyOn(subject.default, 'foo', 'get')
it('foo returns true', () => {
expect(subject.foo).toBe(true)
})
it('foo returns false', () => {
mySpy.mockReturnValueOnce(false)
expect(subject.foo).toBe(false)
})
})
Read more in the docs.
Thanks to #Luke I was able to expand on his answer for my needs. I had the requirements of:
Only mocking certain values in the file - not all
Running the mock only inside a single test.
Turns out that doMock() is like mock() but doesn't get hoisted. In addition requireActual() can be used to grab original data.
My config.js file - I need to mock only part of it
export const SOMETHING = 'blah'
export const OTHER = 'meh'
My test file
// import { someFunc } from 'some/file' // This won't work with doMock - see below
describe('My test', () => {
test('someFunc() does stuff', async () => {
// Here I mock the config file which gets imported somewhere deep in my code
jest.doMock('config.js', () => {
// Grab original
const originalModule = jest.requireActual('config')
// Return original but override some values
return {
__esModule: true, // Depends on your setup
...originalModule,
SOMETHING: 'boom!'
}
})
// Because `doMock` doesn't get hoisted we need to import the function after
const { someFunc } = await import(
'some/file'
)
// Now someFunc will use the original config values but overridden with SOMETHING=boom!
const res = await someFunc()
})
})
Depending on other tests you may also need to use resetModules() somewhere such as beforeAll or afterAll.
Docs:
doMock
requireActual
resetModules
Since we can't override/mock the value directly. we can use the below hack
// foo.js
export const foo = true; // could be expression as well
// spec file
import * as constants from './foo'
Object.defineProperty(constant, 'foo', {value: 1})
For functions:
Object.defineProperty(store, 'doOneThing', {value: jest.fn()})
For me the simplest solution was to redefine the imported object property, as decribed here:
https://flutterq.com/how-to-mock-an-exported-const-in-jest/
// foo.js
export const foo = true; // could be expression as well
// spec file
import * as constants from './foo'
Object.defineProperty(constant, 'foo', {value: 1, writable: true})
Facing the same issue, I found this blog post very useful, and much simpler than #cyberwombat use case :
https://remarkablemark.org/blog/2018/06/28/jest-mock-default-named-export/
// esModule.js
export default 'defaultExport';
export const namedExport = () => {};
// esModule.test.js
jest.mock('./esModule', () => ({
__esModule: true, // this property makes it work
default: 'mockedDefaultExport',
namedExport: jest.fn(),
}));
import defaultExport, { namedExport } from './esModule';
defaultExport; // 'mockedDefaultExport'
namedExport; // mock function
The most common scenario I needed was to mock a constant used by a class (in my case, a React component but it could be any ES6 class really).
#Luke's answer worked great for this, it just took a minute to wrap my head around it so I thought I'd rephrase it into a more explicit example.
The key is that your constants need to be in a separate file that you import, so that this import itself can be stubbed/mocked by jest.
The following worked perfectly for me.
First, define your constants:
// src/my-component/constants.js
const MY_CONSTANT = 100;
export { MY_CONSTANT };
Next, we have the class that actually uses the constants:
// src/my-component/index.jsx
import { MY_CONSTANT } from './constants';
// This could be any class (e.g. a React component)
class MyComponent {
constructor() {
// Use the constant inside this class
this.secret = MY_CONSTANT;
console.log(`Current value is ${this.secret}`);
}
}
export default MyComponent
Lastly, we have the tests. There's 2 use cases we want to handle here:
Mock the generate value of MY_CONSTANT for all tests inside this file
Allow the ability for a specific test to further override the value of MY_CONSTANT for that single test
The first part is acheived by using jest.mock at the top of your test file.
The second is acheived by using jest.spyOn to further spy on the exported list of constants. It's almost like a mock on top of a mock.
// test/components/my-component/index.js
import MyComponent from 'src/my-component';
import allConstants from 'src/my-component/constants';
jest.mock('src/my-component/constants', () => ({
get MY_CONSTANT () {
return 30;
}
}));
it('mocks the value of MY_CONSTANT', () => {
// Initialize the component, or in the case of React, render the component
new MyComponent();
// The above should cause the `console.log` line to print out the
// new mocked value of 30
});
it('mocks the value of MY_CONSTANT for this test,', () => {
// Set up the spy. You can then use any jest mocking method
// (e.g. `mockReturnValue()`) on it
const mySpy = jest.spyOn(allConstants, 'MY_CONSTANT', 'get')
mySpy.mockReturnValue(15);
new MyComponent();
// The above should cause the `console.log` line to print out the
// new mocked value of 15
});
One of the way for mock variables is the follow solution:
For example exists file ./constants.js with constants:
export const CONSTATN_1 = 'value 1';
export const CONSTATN_2 = 'value 2';
There is also a file of tests ./file-with-tests.spec.js in which you need to do mock variables.
If you need to mock several variables you need to use jest.requireActual to use the real values of the remaining variables.
jest.mock('./constants', () => ({
...jest.requireActual('./constants'),
CONSTATN_1: 'mock value 1',
}));
If you need to mock all variables using jest.requireActual is optional.
jest.mock('./constants', () => ({
CONSTATN_1: 'mock value 1',
CONSTATN_2: 'mock value 2'
}));
Instead of Jest and having trouble with hoisting etc. you can also just redefine your property using "Object.defineProperty"
It can easily be redefined for each test case.
This is a pseudo code example based on some files I have:
From localization file:
export const locale = 'en-US';
In another file we are using the locale:
import { locale } from 'src/common/localization';
import { format } from 'someDateLibrary';
// 'MMM' will be formatted based on locale
const dateFormat = 'dd-MMM-yyyy';
export const formatDate = (date: Number) => format(date, dateFormat, locale)
How to mock in a test file
import * as Localization from 'src/common/localization';
import { formatDate } from 'src/utils/dateUtils';
describe('format date', () => {
test('should be in Danish format', () => {
Object.defineProperty(Localization, 'locale', {
value: 'da-DK'
});
expect(formatDate(1589500800000)).toEqual('15-maj-2020');
});
test('should be in US format', () => {
Object.defineProperty(Localization, 'locale', {
value: 'en-US'
});
expect(formatDate(1589500800000)).toEqual('15-May-2020');
});
});
in typescript, you can not overwrite constant value but; you can overwrite the getter function for it.
const mockNEXT_PUBLIC_ENABLE_HCAPTCHAGetter = jest.fn();
jest.mock('lib/constants', () => ({
...jest.requireActual('lib/constants'),
get NEXT_PUBLIC_ENABLE_HCAPTCHA() {
return mockNEXT_PUBLIC_ENABLE_HCAPTCHAGetter();
},
}));
and in the test use as
beforeEach(() => {
mockNEXT_PUBLIC_ENABLE_HCAPTCHAGetter.mockReturnValue('true');
});
Thank you all for the answers.
In my case this was a lot simpler than all the suggestions here
// foo.ts
export const foo = { bar: "baz" };
// use-foo.ts
// this is just here for the example to have a function that consumes foo
import { foo } from "./foo";
export const getFoo = () => foo;
// foo.spec.ts
import "jest";
import { foo } from "./foo";
import { getFoo } from "./use-foo";
test("foo.bar should be 'other value'", () => {
const mockedFoo = foo as jest.Mocked<foo>;
mockedFoo.bar = "other value";
const { bar } = getFoo();
expect(bar).toBe("other value"); // success
expect(bar).toBe("baz"); // fail
};
Hope this helps someone.
../../../common/constant/file (constants file path)
export const Init = {
name: "",
basePath: "",
description: "",
thumbnail: "",
createdAt: "",
endDate: "",
earnings: 0,
isRecurring: false,
status: 0,
};
jest file
jest.mock('../../../common/constant/file',()=>({
get Init(){
return {isRecurring: true}
}
}))
it('showActionbutton testing',()=>{
const {result} = renderHook(() => useUnsubscribe())
expect(result.current.showActionButton).toBe(true)
})
index file
import {Init} from ../../../common/constant/file
const useUsubscribe(){
const showActionButton = Init.isRecurring
return showActionButton
}
I solved this by initializing constants from ContstantsFile.js in reducers. And placed it in redux store. As jest.mock was not able to mock the contstantsFile.js
constantsFile.js
-----------------
const MY_CONSTANTS = {
MY_CONSTANT1: "TEST",
MY_CONSTANT2: "BEST",
};
export defualt MY_CONSTANTS;
reducers/index.js
-----------------
import MY_CONST from "./constantsFile";
const initialState = {
...MY_CONST
}
export const AbcReducer = (state = initialState, action) => {.....}
ABC.jsx
------------
import { useSelector } from 'react-redux';
const ABC = () => {
const const1 = useSelector(state) => state. AbcReducer. MY_CONSTANT1:
const const2 = useSelector(state) => state. AbcReducer. MY_CONSTANT2:
.......
Now we can easily mock the store in test.jsx and provide the values to constant that we want.
Abc.text.jsx
-------------
import thunk from 'redux-thunk';
import configureMockStore from 'redux-mock-store';
describe('Abc mock constants in jest', () => {
const mockStore = configureMockStore([thunk]);
let store = mockStore({
AbcReducer: {
MY_CONSTANT1 ="MOCKTEST",
MY_CONSTANT2 = "MOCKBEST",
}
});
test('your test here', () => { .....
Now when the test runs it will always pick the constant value form mock store.

Undefined is not a constructor Jasmine Enzyme Karma

Hey I have been working in the configuration of karma + jasmine + enzyme to start working in the unit tests of my project, then at exec my first test I got this error
TypeError: undefined is not a constructor (evaluating '(0, _jasmine.expect)(addLoan.length)') in src/app/modules/Login/LoginComponent.spec.js (line 80581)
src/app/modules/Login/LoginComponent.spec.js:80581:29
loaded#http://localhost:9876/context.js:151:17
then here is my test code:
import React from 'react';
import { expect } from 'jasmine';
import { shallow } from 'enzyme';
import ServicerComponent from './LoginComponent';
function setup() {
const props = {
error: {},
onClick: () => {},
emailOnChange: () => {},
passwordOnChange: () => {},
};
return shallow(<ServicerComponent{...props} />);
}
describe('<ServicerComponent />', () => {
const displayNames = {
login: 'login',
};
let wrapper;
beforeEach(() => {
wrapper = setup();
});
it('should have a Login button', () => {
const addLoan = wrapper.find({ name: displayNames.login });
expect(addLoan.length).toBe(1);
});
});
also I am using :
jasmine: 2.5.3
enzyme: 2.7.1
You need to create setup instance of the class
beforeEach(() => {
wrapper = new setup();
});
I already found the answer of the question, I just remove the jasmine importer and add a global variable in the .eslintrc.json named expect equal true

Categories