TypeError: Cannot read property 'getters' of undefined on Vue Jest Test - unit-testing

This is my test file
import { shallowMount, createLocalVue } from '#vue/test-utils';
import Home from '#/views/Home.vue';
import Vuex from 'vuex';
import Vuetify from 'vuetify';
import movies from '#/store/modules/movies';
const localVue = createLocalVue();
localVue.use(Vuex);
describe('Home.vue', () => {
let vuetify;
let store;
let state;
let actions;
beforeEach(() => {
state = {
movieList: [],
movieDetails: {},
};
actions = {
getMovieList: jest.fn(),
getMovieDetails: jest.fn(),
};
store = new Vuex.Store({
modules: {
movies: {
namespaced: true,
state,
actions,
},
},
});
vuetify = new Vuetify();
});
const wrapper = shallowMount(Home, {
store,
vuetify,
localVue,
});
it('should call submitForm() function when button is clicked', () => {
wrapper.find('button').trigger('click');
expect(wrapper.vm.submitForm).toHaveBeenCalled();
});
});
This is my view file
<script>
import Tooltip from '#/components/Tooltip.vue';
import { moviesComputed, moviesMethods } from '#/store/helpers/movies';
export default {
components: {
Tooltip,
},
methods: {
...moviesMethods,
submitForm() {
const validate = this.$refs.form.validate();
if (!validate) return;
this.currentPage = 1;
this.getMoviesList({ s: this.searchQuery });
},
async goToDetails(moveId) {
this.$router.push({ name: 'MovieDetails', params: { id: moveId } });
},
onScroll() {
const isOnBottom = document.documentElement.scrollTop + window.innerHeight
=== document.documentElement.offsetHeight;
if (isOnBottom) {
this.currentPage += 1;
this.nextMoviePage({ s: this.searchQuery, page: this.currentPage });
}
},
},
computed: {
...moviesComputed,
pagedMovieList() {
const listNumber = this.maxList * this.currentPage;
const list = this.movieList.filter((movie, index) => index < listNumber);
return list;
},
},
data() {
return {
searchQuery: '',
queryRules: [(v) => !!v || 'Antes de pesquisar, forneça um nome'],
mouseOverIndex: '',
maxList: 6,
currentPage: 1,
};
},
async mounted() {
document.addEventListener('scroll', this.onScroll);
},
beforeDestroy() {
document.removeEventListener('scroll', this.onScroll);
},
};
</script>
<template>
<div id="home">
<v-row class="justify-center align-center">
<v-col class="home-form" :class="{ 'to-top': movieList.length }" sm="12" md="6" xl="4">
<v-form ref="form" color="secondary" #submit="submitForm">
<v-text-field
label="Digite sua busca"
append-icon="mdi-magnify"
:rules="queryRules"
v-model="searchQuery"
required
/>
</v-form>
<v-btn color="secondary" class="mt-1" #click="submitForm">Enviar</v-btn>
</v-col>
</v-row>
<v-row class="mt-5">
<v-col
cols="12"
sm="6"
md="4"
v-for="(movie, index) in pagedMovieList"
:key="`${movie.Title}-${index}`"
style="position: relative"
>
<v-card elevation="10" #mouseover="mouseOverIndex = index" #mouseout="mouseOverIndex = ''">
<p class="mt-1 text-center" v-if="movie.Poster === 'N/A'">{{ movie.Title }}</p>
<v-img v-if="movie.Poster !== 'N/A'" :src="movie.Poster" />
<v-img v-else src="#/assets/not-found.png" />
<Tooltip #clicked="goToDetails" :active="index === mouseOverIndex" :movie="movie" />
</v-card>
</v-col>
</v-row>
</div>
</template>
This is my store module file
import { GetList, GetDetails } from '#/services/movies';
export const state = {
movieList: [],
movieDetails: {},
};
export const mutations = {
SET_LIST(state, newList) {
state.movieList = newList;
},
SET_MOVIE_DETAILS(state, newValue) {
state.movieDetails = newValue;
},
ADD_TO_LIST(state, list) {
state.movieList.push(...list);
},
};
export const actions = {
async getMoviesList({ commit }, query) {
const resp = await GetList(query);
if (resp.status === 200) commit('SET_LIST', resp.data.Search);
},
async getMovieDetails({ commit }, movieId) {
const resp = await GetDetails({ i: movieId });
if (!resp.status === 200) return;
commit('SET_MOVIE_DETAILS', resp.data);
},
async nextMoviePage({ commit }, query) {
const resp = await GetList(query);
if (resp.status === 200 && resp.data.Search) commit('ADD_TO_LIST', resp.data.Search);
},
};
const movies = {
namespaced: true,
mutations,
state,
actions,
};
export default movies;
This is my base.js module file
export const state = {
isLoading: false,
};
export const mutations = {
SET_LOADING(state, newValue) {
state.isLoading = newValue;
},
};
export const actions = {
setLoading({ commit }, value) {
commit('SET_LOADING', value);
},
};
const base = {
namespaced: true,
mutations,
state,
actions,
};
export default base;
And this is my store.js
import Vue from 'vue';
import Vuex from 'vuex';
// Modules
import Base from './modules/base';
import Movies from './modules/movies';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
base: Base,
movies: Movies,
},
strict: process.env.NODE_ENV !== 'production',
});
This is the error
TypeError: Cannot read property 'getters' of undefined
8 | Vue.use(Vuex);
9 |
> 10 | export default new Vuex.Store({
| ^
11 | modules: {
12 | base: Base,
13 | movies: Movies,
I have no idea why I'm getting an error on new Vuex.Store on tests. This application runs normally, without errors on Vuex. I cant even post what I already did to solve this because I'm completely lost

Related

TypeError: null is not an object (evaluating 'RNFusedLocation.getCurrentPosition')

Please, am new to react native. Am trying to get the current location through google places autocomplete for android in expo but an getting the error 'TypeError: null is not an object (evaluating 'RNFusedLocation.getCurrentPosition')'
below is my code
Please, am new to react native. Am trying to get the current location through google places autocomplete for android in expo but an getting the error 'TypeError: null is not an object (evaluating 'RNFusedLocation.getCurrentPosition')'
below is my code
App.js
import { StyleSheet, Text, View, StatusBar, PermissionsAndroid, Platform,} from 'react-native';
import HomeScreen from './src/screens/HomeScreen/HomeScreen';
import DestinationSearch from './src/screens/DestinationSearch/DestinationSearch';
import SearchResults from './src/screens/SearchResults/SearchResults';
import { useEffect, useState } from 'react';
//import * as Location from 'expo-location';
import Geolocation, { getCurrentPosition } from 'react-native-geolocation-service';
navigator.geolocation = require('react-native-geolocation-service');
export default function App() {
const androidPermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: "Uber App location Permission",
message:
"Uber App needs access to your location " +
"so you can take awesome rides.",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK"
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can use the location");
} else {
console.log("Location permission denied");
}
} catch (err) {
console.warn(err);
}
};
useEffect(() => {
if (androidPermission) {
Geolocation.getCurrentPosition(
(position) => {
console.log(position);
},
(error) => {
// See error code charts below.
console.log(error.code, error.message);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
}
}, [])
useEffect(() => {
if(Platform.OS == 'android') {
androidPermission()
} else{
//IOS
Geolocation.requestAuthorization();
}
}, [])
return (
<View>
{/* <HomeScreen /> */}
<DestinationSearch />
{/* <SearchResults /> */}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
marginTop:StatusBar.currentHeight
},
});
`
DestinationSearch.jsx
import { View, Text, StyleSheet, SafeAreaView, StatusBar } from 'react-native'
import React, {useEffect, useState,} from 'react'
import { GooglePlacesAutocomplete } from 'react-native-google-places-autocomplete';
import {GOOGLE_MAPS_APIKEY} from '#env'
import PlaceRow from './PlaceRows';
const DestinationSearch = () => {
const [originPlace,setOriginPlace] = useState(null)
const [destinationPlace, setDestinationPlace] = useState(null)
useEffect(() => {
console.log('useEffect is called')
if (originPlace && destinationPlace) {
console.warn('Redirect to results')
}
}, [originPlace, destinationPlace])
return (
<SafeAreaView>
<View style={styles.container}>
<GooglePlacesAutocomplete
nearbyPlacesApi = 'GooglePlacesSearch'
placeholder = 'From...'
listViewDisplayed = 'auto'
debounce = {400}
currentLocation = {true}
currentLocationLabel='Current location'
minLenght = {2}
enabledPoweredByContainer = {true}
fetchDetails = {true}
autoFoccus = {true}
renderRow={(data)=> <PlaceRow data={data}/>}
query ={{
key: GOOGLE_MAPS_APIKEY ,
language :'en'
}}
styles={{
container: styles.autocompleteContainer,
textInput: styles.textInput,
listView: styles.listView,
seperator: styles.separator
}}
onPress = {(data, details = null)=> {
setOriginPlace({data, details})
console.log(currentLocation)
}}
/>
<GooglePlacesAutocomplete
nearbyPlacesApi = 'GooglePlacesSearch'
placeholder = 'To...'
listViewDisplayed = 'auto'
debounce = {400}
minLenght = {2}
enabledPoweredByContainer = {true}
fetchDetails = {true}
autoFoccus = {true}
query ={{
key: GOOGLE_MAPS_APIKEY ,
language :'en'
}}
renderRow={(data)=> <PlaceRow data={data}/>}
styles={{
container: {
...styles.autocompleteContainer,
top: 70
},
textInput: styles.textInput,
seperator: styles.separator
}}
onPress = {(data, details = null)=> {
setDestinationPlace({data, details})
}}
/>

How can I mock a paginated GraphQL query?

I am using apollo/client and graphql-tools/mock to auto mock graphql queries and test React Native components that use them. My schema is generated from an introspection query created by graphql-codegen. For the most part, my queries are getting mocked by addMocksToSchema just fine. However I have a query that is not returning any mock data.
The query is paginated and doesn't follow the same structure of the examples in the docs (https://www.graphql-tools.com/docs/mocking). Instead of having a query with a node that has a field that is a connection type, the connection is returned from the query. This means I can't use relayStylePaginationMock to mock my function because the resolver argument of addMocksToSchema expects the nodes to be objects not functions(function is the return type of relayStylePaginationMock).
In the below code I have tried overriding the newsPost query with a resolver, but I can't figure out how to get the NewsPostEdges from the store and put them in my mock. Everything I have tried has broken the mock and caused it to return undefined for the whole mocked query.
Why does a paginated mock not work by default?
How can I mock this query?
Schema:
type Query {
newsPost: NewsPostConnection
}
type NewsPostConnection {
totalCount: Int
edges: [NewsPostEdge]!
pageInfo: PageInfo!
}
type NewsPostEdge {
node: NewsPostNode
cursor: String!
}
type NewsPostNode {
newsPostId: Int!
isPinned: Boolean!
label: String
title: String
content: String
postType: NewsPostType!
createdDate: DateTime
createdDateTime: String
creator: UserNode!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
endCursor: String
startCursor: String
}
News Posts query:
query NewsPosts(
$after: String
$first: Int
$newsPostId: Filter_ID
$sort: [NewsPostSortEnum]
$isPinned: Filter_Boolean
) {
newsPosts(
after: $after
first: $first
newsPostId: $newsPostId
sort: $sort
isPinned: $isPinned
) {
pageInfo {
hasNextPage
endCursor
}
edges {
post: node {
newsPostId
postType
isPinned
label
createdDateTime
creator {
initials
avatarUrl
displayName
}
content
}
}
}
}
newsPostsContent.test.tsx
import React from 'react';
import { waitFor } from '#testing-library/react-native';
import { PartialDeep } from 'type-fest';
import { faker } from '#faker-js/faker';
import { createFakeUser, render } from '#root/unit-tests/#util';
import { NewsPostNode, NewsPostType } from '#root/src/generated';
import NewsPostContent from '../NewsPostContent';
const mocks = {
NewsPostNode: (): PartialDeep<NewsPostNode> => {
const postId = faker.random.numeric(4);
const createdDate = faker.date.recent(10);
return {
postId,
isPinned: true,
label: 'test',
content: `<div><p>${faker.random.words(10)}</p></div>`,
postType: NewsPostType.Announcement,
createdDate: createdDate.toISOString(),
createdDateTime: createdDate.toISOString(),
};
},
UserNode: createUserPerson(),
};
describe('Dashboard News', () => {
it('renders dashboard news', async () => {
const { getByTestId, debug } = render(
<NewsPostContent />,
mocks,
);
await waitFor(() => [debug(), expect(getByTestId('newsPostContent:Card')).toBeDefined()]);
});
});
NewsPostsContetnt.tsx
const NewsPostContent = () => {
const [newsPostList, setNewsPostList] = useState<PartialDeep<NewsPostNode>[]>([])
const {
data,
loading,
refetch: refetchPosts,
} = useNewsPostsQuery({
variables: { first: MAX_POSTS, isPinned: true, sort: [PostSortEnum.CreatedDateDesc] },
});
console.log(data); // <-- returns undefined when mock breaks
useEffect(() => {
const newsPostEdges = data?.newsPosts?.edges ?? [];
const newsPostNodes = newsPostEdges.reduce((posts, newsPostNode) => {
if (newsPostNode?.post) {
posts.push(newsPostNode.post);
}
return posts;
}, [] as PartialDeep<NewsPostNode>[]);
setNewsPostList(newsPostNodes);
}, [data]);
return (
{<View>
// Component UI to render posts
</View>}
)
}
AutoMockedProvider.tsx
import React from 'react';
import { ApolloProvider, ApolloClient, InMemoryCache } from '#apollo/client';
import { buildClientSchema } from 'graphql';
import {
addMocksToSchema,
createMockStore,
IMocks,
IMockStore,
relayStylePaginationMock,
} from '#graphql-tools/mock';
import { SchemaLink } from '#apollo/client/link/schema';
import { faker } from '#faker-js/faker';
const introspectionResult = require('../../src/generated/introspection.json');
const defaultMocks = {
Date: () => faker.date.recent().toISOString(),
DateTime: () => faker.date.recent().toISOString(),
};
const resolvers = (store: IMockStore) => ({
Query: {
newsPosts: (root, { isPinned, after, first, postId, sort }) => {
return {
edges: (ref) => {
const connectionsRef = store.get('NewsPostConnection');
const edgesRef = store.get(connectionsRef, 'edges');
return edgesRef; // <-- this breaks the mock
},
pageInfo: {
endCursor: null,
hasNextPage: false,
},
};
},
},
});
const AutoMockedProvider = ({
mocks = {},
children,
}: React.PropsWithChildren<{ mocks?: IMocks }>) => {
const schema = buildClientSchema(introspectionResult);
const store = createMockStore({ mocks: { ...defaultMocks, ...mocks }, schema });
const schemaWithMocks = addMocksToSchema({
schema,
mocks: {
...defaultMocks,
...mocks,
},
resolvers,
preserveResolvers: false,
store,
});
const client = new ApolloClient({
link: new SchemaLink({ schema: schemaWithMocks }),
cache: new InMemoryCache(),
});
return <ApolloProvider client={client}>{children}</ApolloProvider>;
};
export default AutoMockedProvider;

How to capture object props in Vue snapshot tests

I always get [object Object] in place of object props due to object to string coercion when I use snapshot testing. How can I fix it? I've tried wrapping element into JSON.stringify(), but it causes "Converting circular structure to JSON" Error.
The example of a resulting snapshot:
exports[`SalesList.vue Снапшот десктоп 1`] = `
<magic-grid-stub
class="sales-list"
cols="[object Object]"
gaps="[object Object]"
usemin="true"
>
<sales-item-stub
class="item"
sale="[object Object]"
/>
<sales-item-stub
class="item"
sale="[object Object]"
/>
<sales-item-stub
class="item"
sale="[object Object]"
/>
<sales-item-stub
class="item"
sale="[object Object]"
/>
<sales-info-stub
class="item"
content="additionalInfo"
/>
</magic-grid-stub>
`;
I have the simple corresponding snapshot tests, like this one:
import { createLocalVue, shallowMount } from '#vue/test-utils'
import SalesList from '#/components/sales/SalesList.vue'
let localVue
const fakeSale = {
code: 'code',
description: 'description',
title: 'title',
image: 'image',
archive: false,
visible: true,
date_to: '2020/08/01',
short_description: 'short_description',
slug: 'slug',
date_from: '2020/06/01',
seo: {
seo_description: 'seo_description',
seo_title: 'seo_title',
seo_keywords: 'seo_keywords',
},
}
function createWrapper(component, options) {
return shallowMount(component, {
localVue,
...options,
})
}
beforeAll(() => {
localVue = createLocalVue()
})
describe('SalesList.vue', () => {
it('Снапшот десктоп', async () => {
expect.assertions(1)
const wrapper = createWrapper(SalesList, {
propsData: {
sales: Array.from({ length: 4 }, (_, index) => ({
...fakeSale,
slug: `slug-${index}`,
})),
additionalInfo: 'additionalInfo',
},
mocks: {
$device: { isDesktop: true },
},
})
expect(wrapper.element).toMatchSnapshot()
})
})
And the component in question itself:
<script lang="ts">
import SalesItem from '#/components/sales/SalesItem.vue'
import MagicGrid from '#/components/MagicGrid.vue'
import SalesInfo from '#/components/sales/SalesInfo.vue'
import Vue from 'vue'
export default Vue.extend({
name: 'SalesList',
components: {
SalesItem,
MagicGrid,
SalesInfo,
},
props: {
sales: {
type: Array,
required: true,
},
additionalInfo: {
type: String,
default: null,
},
},
computed: {
colsAndGaps(): {
cols: { 0: number }
gaps: { 0: number }
} {
return this.$device.isDesktopOrTablet
? {
cols: {0: 2},
gaps: {0: 30},
}
: {
cols: {0: 1},
gaps: {0: 16},
}
},
},
})
</script>
<template>
<magic-grid v-bind="colsAndGaps" class="sales-list">
<sales-item
v-for="sale in sales"
:key="sale.slug"
:sale="sale"
class="item"
/>
<sales-info v-if="additionalInfo" :content="additionalInfo" class="item"/>
</magic-grid>
</template>
You could use a custom jest snapshot serializer.
For VueJs 2 you could use https://github.com/tjw-lint/jest-serializer-vue-tjw - but it doesn't work for VueJs 3 (https://github.com/tjw-lint/jest-serializer-vue-tjw/pull/64).
Example configuration for VueJs 2:
npm install jest-serializer-vue-tjw
// package.json
{
...
"jest": {
"snapshotSerializers": ["jest-serializer-vue-tjw"]
}
}

How to fix Jest error : TypeError: $ is not a function

I am writing unit test cases for a Vue.js component.
When I am trying to shallowMount component using vue-test-util I get an error:
TypeError: $ is not a function at VueComponent.mounted
(src/components/gridComponent/index.vue:7579:7)
My code:
import $ from 'jquery';
global['$'] = global['jQuery'] = $;
import { shallowMount, createLocalVue } from '#vue/test-utils'
import gridComponent from '#/components/gridComponent/index'
describe('grid view component', () => {
it('has the expected HTML structure', async () => {
let wrapper = await shallowMount(gridComponent, {
stubs: ['GridLayout', 'GridItem'],
propsData: {componentsList}
})
expect(wrapper.element).toMatchSnapshot()
})
})
Below is the code of gridComponent:
import * as $ from 'jquery'
export default {
name: 'gridComponent',
components: { GridLayout, GridItem, DxpCommonModal },
props: ['componentsList'],
watch: {
componentsList: function (newVal, oldVal) {
// eslint-disable-next-line
this.matchingComponents = this.componentsList
}
},
data () {
return {
isDraggable: true,
isResizable: true
}
},
created () {
},
computed: {
...mapGetters(['getResources'])
},
mounted () {
$('#headerComponent').html(this.getSelectorHTML(this.siteDetails.header))
$('#footerComponent').html(this.getSelectorHTML(this.siteDetails.footer))
this.addHtmlOfComponentsInAPage()
},
destroyed () {
},
methods: {
addHtmlOfComponentsInAPage () {
this.selectedPage.Components.forEach((element, index) => {
$('#${index}').html(this.getSelectorHTML(this.selectedPage.Components[index]))
})
},
getSelectorHTML (component) {
const element = document.createElement(component.componentType)
element.setAttribute('content-id', new Date().getTime().toString())
if (!this.values && component.demoData) {
this.values = component.demoData
}
if (this.values) {
this.createMarkup(element, this.values)
this.values = ''
}
return element
}
}
}
Troubleshooting
In the component, try
const $ = require('jquery')
Put this before the usage in the method causing the error.
This will let you know if you are un-defining or redefining it somewhere.
Solution 2
You may need jsdom.
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM(`<!DOCTYPE html>`);
const $ = require('jquery')(window);

While running react component test in a react-redux app, "Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_0__compose__.a.apply(...) is not a function"

I have a react-redux application, in which i am trying to run test cases for a react component something like below:
class Login extends Component {
componentWillMount() {
this.props.checkUserAuth();
}
componentDidMount() {
this.props.getEnvConfig();
}
componentDidUpdate() {
if (!this.props.isAuthenticating && this.props.isAuthenticated) {
hashHistory.push('/dashboard');
}
}
getAbc() {
return this.props.abc;
}
anotherLogin() {
return () => {
const anotherURL = `${this.props.envConfig.AuthUrl}?response_type=code&client_id=${this.props.envConfig.ClientId}&redirect_uri=${this.props.envConfig.CallbackUri}&state=8.0`;
/* global window */
window.location.assign(anotherURL);
};
}
myLogin() {
return () => {
const loginUrl = `${this.props.envConfig.AuthUrl}?
scope=urlScope&client_id=${this.props.envConfig.ClientId}&redirect_uri
=${this.props.envConfig.RedirectUri}&response_type=token`;
/* global window */
window.location.assign(loginUrl);
};
}
render() {
if (this.props.isAuthenticating && !this.props.isAuthenticated) {
return (<div>loading</div>); // needs to implement and include loading
component
} else if (!this.props.isAuthenticating && !this.props.isAuthenticated) {
return (
<Grid fluid="true">
<Row>
<Col md={6} bsClass="xyz">
<div className="left-login-container">
<LoginLeft
logo={logo}
box={box}
abc={this.abc()}
/>
</div>
</Col>
<Col md={6} bsClass="xyz">
<div className="right-login-container">
<LoginRight
myLogin={this.myLogin()}
anotherLogin={this.anotherLogin()}
/>
</div>
</Col>
</Row>
</Grid>
);
}
return null;
}
}
Login.defaultProps = {
abc: '0',
getEnvConfig: () => {},
envConfig: {
sfdcAuthUrl: '',
sfdcCallbackUri: '',
sfdcClientId: '',
},
isAuthenticating: true,
isAuthenticated: false,
checkUserAuth: () => {},
};
Login.propTypes = {
abc: PropTypes.string.isRequired,
getEnvConfig: PropTypes.func.isRequired,
envConfig: PropTypes.shape({
AuthUrl: PropTypes.string.isRequired,
CallbackUri: PropTypes.string.isRequired,
ClientId: PropTypes.string.isRequired,
}),
isAuthenticating: PropTypes.bool.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
checkUserAuth: PropTypes.func.isRequired,
};
function mapDispatchToProps(dispatch) {
return {
myLogin: (data) => {
dispatch(myLogin(data));
},
getEnvConfig: () => {
dispatch(getEnvConfig());
},
checkUserAuth: () => {
dispatch(getUserInfo());
},
};
}
function mapStateToProps(state, ownProps) {
return {
abc: state.Login.Summary.Report,
envConfig: state.EnvConfig.envConfig,
isAuthenticating: state.Auth.isAuthenticating,
isAuthenticated: state.Auth.isAuthenticated,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);
I am going somewhere wrong in mocking the store and creating the shallow for his login component before even writing a test case i am getting the error "Uncaught TypeError: WEBPACK_IMPORTED_MODULE_0__compose.a.apply(...) is not a function" Not sure abt the reason behind it. Here is the spec file content:
import React from 'react';
import { createStore, applyMiddleware } from 'redux';
import { shallow, mount } from 'enzyme';
import configureStore from 'redux-mock-store';
import LoginReducer from '../../../reducers/rootReducers';
import thunk from 'redux-thunk'
import Login from './LoginPage';
const mockStore = configureStore([LoginReducer]);
const initialState = {
SummaryStats: {
Reports: '0',
},
isAuthenticated: false,
isAuthenticating: true,
userInfo: {
firstName: 'Ruchir',
},
envConfig: {},
};
const store = mockStore(initialState);
const dummyData = {
abc: '0',
getEnvConfig: () => {},
envConfig: {
AuthUrl: '',
CallbackUri: '',
ClientId: '',
},
};
const LoginWrapper = shallow(<Login
store={store}
{...dummyData}
/>);
describe('<Login />', () => {
it('check componentDidMount method', () => {
LoginWrapper.componentDidMount();
expect(LoginWrapper.props().getEnvConfig).toHaveBeenCalled();
});
});