Mock destructed import with Jest? - jestjs

I'm trying to mock a destructed import with Jest.
In the component is the destructed import:
import { getSomething } from 'utils/paymentUtils';
In the test:
import React from 'react';
import { shallow } from 'enzyme';
import Component from 'components/Component';
import * as utils from 'utils/paymentUtils';
jest.mock('utils');
describe('Something', () => {
let wrapper;
utils.getSomething.mockImplementation(() => 'Blah');
The error I'm getting is:
Cannot find module 'utils' from 'Component.spec.js'

You have to mock the module itself, in this case utils/paymentUtils

Related

reactjs - sidebar not working after store update

I am using reactjs.
node: version 14
I am developing on core-ui-react-template.
Sidebar did not work after updating the ./store file. I put the contents of the store file and index.js file below.
original website core.io
I have been working on it for a few days but I could not get any results. I couldn't find where was the mistake
index.js
import 'react-app-polyfill/ie11'; // For IE 11 support
import 'react-app-polyfill/stable';
import './polyfill'
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { icons } from './assets/icons'
import store from './store'
import { transitions, positions, Provider as AlertProvider } from 'react-alert'
import AlertTemplate from 'react-alert-template-basic'
import {Provider} from 'react-redux';
import ReactNotification from 'react-notifications-component';
import 'react-notifications-component/dist/theme.css'
React.icons = icons;
const options = {
position: positions.BOTTOM_RIGHT,
timeout: 5000,
offset: '1px',
transition: transitions.SCALE,
};
console.log(store.getState());
ReactDOM.render(
<Provider store={store}>
<AlertProvider template={AlertTemplate} {...options}>
<ReactNotification/>
<App/>
</AlertProvider>
</Provider>,
document.getElementById('root')
);
serviceWorker.unregister();
./store.js
import {applyMiddleware, combineReducers, compose, createStore} from "redux";
import customerReducer from "./components/helpers/reducers/customerReducer";
import userReducer from "./components/helpers/reducers/userReducer";
import appointmentsReducer from "./components/helpers/reducers/appointmenstReducer";
import thunk from "redux-thunk";
const initialState = {
sidebarShow: 'responsive'
};
const changeStateReducer = (state = initialState, { type, ...rest }) => {
switch (type) {
case 'set':
return {...state, ...rest };
default:
return state
}
};
const rootReducers = combineReducers({
customerInfo: customerReducer,
account_profile: userReducer,
appointmentsList: appointmentsReducer,
changeState: changeStateReducer
});
const allEnhancers = compose(
applyMiddleware(thunk)
);
const store = createStore(
rootReducers,
allEnhancers
);
export default store
As you know, I use core-ui-react template. There is a link below.
But after updating the ./store file, it shows "undefined" when I show it with console.log (sidebarShow) in "const sidebarShow = useSelector (state => state.sidebarShow)" line in TheHeader file.
https://github.com/coreui/coreui-free-react-admin-template/blob/master/src/containers/TheHeader.js
I think "useSelector (state => state.sidebarShow)" doesn't get the function here. It originates from here.
check out how combineReducers works: https://redux.js.org/api/combinereducers
your selector should be:
const sidebarShow = useSelector(state => state.changeState.sidebarShow)
you'll notice that changeState is not a very good key name, but that is another issue :)

How to import rxjs static functions with Node 12 import?

I am trying out the new Node 12 module import syntax and cannot get static functions from rxjs to work.
I've tried both Typescript-style import syntax and ideas from the new module documentation.
// SyntaxError: The requested module 'rxjs' does not provide an export named 'interval'
import { interval } from 'rxjs';
const x = interval(1000)
// TypeError: interval is not a function
import interval from 'rxjs';
const x = interval(1000)
// TypeError: interval is not a function
import interval from 'rxjs/observable/interval.js';
const x = interval(1000)
Any idea what the correct way is to import static functions?
UPDATE: One way that works:
import Observable from 'rxjs';
const x = Observable.interval(1000).subscribe(() =>
console.log('' + new Date().toISOString())
)

Unable to resolve "firebase" from "src\containers\Login.js"

I got this error when i run the exp start command. How can I solve this error?
This is my login.js file code.
I am new to React native, using js to run a native app using expo, so I am stuck. I don't know why it gives me this error and how to handle it.
import React, { Component } from 'react';
import {
Alert,
StyleSheet,
Text,
View,
TextInput,
TouchableOpacity,
Image,
AsyncStorage,
KeyboardAvoidingView,
Dimensions,
ActivityIndicator,
NetInfo,
BackHandler,
DeviceEventEmitter
} from 'react-native';
import * as firebase from 'firebase';
import firebaseService from '../config/firebaseService';
import {Actions} from 'react-native-router-flux';
import Modal from "react-native-modal";
import { Dialog,ConfirmDialog } from 'react-native-simple-dialogs';
import Toast, {DURATION} from 'react-native-easy-toast';
import Expo from 'expo';
var height = Dimensions.get('window').height;
var width = Dimensions.get('window').width;
import styles from "../styles/loginStyle";
import {apiUrl,netErrorMsg,facebookId,androidGoogleClientId,iosGoogleClientId,firebaseConfig} from "../config/constant";
export default class Login extends Component<{}> {
constructor(props) {
super(props);
this.state = {
email:'',
password:'',
forgotEmail:'',
versionName:'',
loading:false,
isModalVisible: false,
netStatus:'none',
dialogVisible:false,
errorForgotEmail:""
}
}
Looks like you are trying to import firebase from your Login.js in some file. Remove that import and import firebase as you have imported it in your Login.js. This will resolve the problem.

flowjs not recognizing import with #

I am trying to import #aws/dynamo-data-mapper package from AWS. flow isn't recognizing the packages with #.
// #flow
import Joi from 'joi';
import { DataMapper } from '#aws/dynamo-data-mapper';
import DynamoDB from 'aws-sdk/clients/dynamodb';
Running flow is giving below error
Cannot resolve module #aws/dynamo-data-mapper.
1│ // #flow
2│ import Joi from 'joi';
3│ import { DataMapper } from '#aws/dynamo-data-mapper';
4│ import DynamoDB from 'aws-sdk/clients/dynamodb';
Wondering how to make flow recognize the packages that start with #.

React.js unit testing with d3-npm

I am creating a forced graph in react using d3 for npm.
The graph is created using the follows:
https://medium.com/walmartlabs/d3v4-forcesimulation-with-react-8b1d84364721
I am trying to set up the testing environment as follows:
https://ericnish.io/blog/how-to-unit-test-react-components-with-enzyme/
the problem is when I run the test I keep on getting
Cannot read property 'matches' of undefined
at C:\workspace\project\node_modules\d3-selection\build\d3-selection.js:83:15
I have imported d3 in my graph component as follows:
import * as d3 from 'd3';
It seems like when I import my react component in my test file, it freaks out. This is my test file:
import React from 'react'
import {shallow, mount, render} from 'enzyme'
import {expect} from 'chai'
import * as d3 from 'd3';
import graph from '.../components/graph ';
describe('graph ', () => {
it('should have the main svg', (done) => {
const wrapper = shallow(<graph />);
expect(wrapper.find('svg')).to.have.length(1);
done()
})
})
How can I get rid of this error?
Create a file, e.g. polyfill.js:
global.document.documentElement = {matches: () => false};
And import it right before you import DS3 (or any other import that transitively imports D3):
import React from 'react'
import {shallow, mount, render} from 'enzyme'
import {expect} from 'chai'
import './polyfill';
import * as d3 from 'd3';

Resources