React Native Test with Jest impossible to mock Geolocation - testing

I tried to find a solution on the web and I found this Stackoverflow answer, I followed the instructions but I was blocked:
TypeError: Cannot set property 'geolocation' of undefined
So when I remove the solution my error is:
ReferenceError: navigator is not defined
My package.json looks like this:
"dependencies": {
"eslint-plugin-react-native": "^3.2.0",
"prop-types": "^15.6.0",
"react": "16.0.0",
"react-native": "0.51.0",
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-eslint": "^8.1.2",
"babel-jest": "^22.4.1",
"babel-preset-react-native": "4.0.0",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"eslint": "^4.14.0",
"eslint-plugin-react": "^7.5.1",
"jest": "^22.4.2",
"jest-enzyme": "^6.0.0",
"react-dom": "^16.2.0",
"react-scripts": "^1.1.1",
"react-test-renderer": "16.0.0-beta.5"
},
"jest": {
"preset": "react-native",
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
],
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-navigation)"
],
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/assetsTransformer.js",
"\\.(css|less)$": "<rootDir>/assetsTransformer.js"
},
"verbose": true
},
"plugins": [
"react",
"react-native"
],
"ecmaFeatures": {
"jsx": true
},
"env": {
"react-native/react-native": true
}
And my test is just:
test('Map Component', () => {
// create the snapshot
const tree = renderer.create(<Map/>).toJSON();
// test the snapshot
expect(tree).toMatchSnapshot();
});
The error is on this line, on the navigator:
navigator.geolocation.getCurrentPosition((position) => {
For the moment I am not testing my component with the navigator. I hope some of you have a solution, please.

Add this in your jest setup.js:
global.navigator = {
geolocation: {
clearWatch: jest.fn(),
getCurrentPosition: jest.fn((success, failure, options) => {
success({
coords: {
longitude: 60,
latitude: 60,
},
});
}),
stopObserving: jest.fn(),
watchPosition: jest.fn(),
},
};
The setup.js file is the one you specify in your package.json file. i.e:
"jest": {
"setupFiles": [
"<rootDir>/__tests__/setup.js"
],
...

Related

Rails Vue2 Jest SyntaxError: Cannot use import statement outside a module

I have a Rails application with Vue and when I installed Jest and tried to run my Menu_Filter.test.js test, I got this error. I tried many solutions, but nothing worked.
Error:
My package.json in which I configured Jest:
{
"name": "immomapper-frontend",
"version": "0.1.0",
"dependencies": {
"#rails/actioncable": "^6.0.0",
"#rails/activestorage": "^6.0.0",
"#rails/ujs": "^6.0.0",
"#rails/webpacker": "5.4.3",
"#vue/composition-api": "^1.2.4",
"#vueform/multiselect": "^2.2.0",
"#vueform/slider": "^2.0.5",
"babel": "^6.23.0",
"babel-jest": "^27.2.5",
"jest": "^27.2.5",
"leaflet": "^1.7.1",
"turbolinks": "^5.2.0",
"vue": "^2.6.14",
"vue-loader": "^15.9.8",
"vue-template-compiler": "^2.6.14",
"vue2-leaflet": "^2.7.1",
"webpack": "^4.46.0",
"webpack-cli": "^3.3.12"
},
"devDependencies": {
"#babel/core": "^7.15.8",
"#babel/preset-env": "^7.15.8",
"#vue/babel-preset-app": "^4.5.14",
"#vue/cli-plugin-unit-jest": "~4.5.0",
"#vue/test-utils": "^1.2.2",
"babel-core": "^7.0.0-bridge.0",
"vue-jest": "^3.0.7",
"webpack-dev-server": "^3"
},
"scripts": {
"test": "jest"
},
"jest": {
"roots": [
"app/javascript/spec"
],
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"moduleNameMapper": {
"^#/(.*)$'": "<rootDir>/src/$1"
},
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.vue$": "vue-jest"
},
"testEnvironment": "jsdom"
}
}
My test file:
import { mount, shallowMount } from '#vue/test-utils'
import Filter from '../components/Menu_filter'
test('Filter exists', () => {
const wrapper = mount(Filter);
expect(wrapper.is(Filter)).toBe(true)
})
Lastly, my babel.config.js:
module.exports = function(api) {
var validEnv = ['development', 'test', 'production']
var currentEnv = api.env()
var isDevelopmentEnv = api.env('development')
var isProductionEnv = api.env('production')
var isTestEnv = api.env('test')
if (!validEnv.includes(currentEnv)) {
throw new Error(
'Please specify a valid `NODE_ENV` or ' +
'`BABEL_ENV` environment variables. Valid values are "development", ' +
'"test", and "production". Instead, received: ' +
JSON.stringify(currentEnv) +
'.'
)
}
return {
presets: [
isTestEnv && [
'#babel/preset-env',
{
targets: {
node: 'current'
}
}
],
(isProductionEnv || isDevelopmentEnv) && [
'#babel/preset-env',
{
forceAllTransforms: true,
useBuiltIns: 'entry',
corejs: 3,
modules: auto,
exclude: ['transform-typeof-symbol']
}
]
].filter(Boolean),
plugins: [
'babel-plugin-macros',
'#babel/plugin-syntax-dynamic-import',
isTestEnv && 'babel-plugin-dynamic-import-node',
'#babel/plugin-transform-destructuring',
[
'#babel/plugin-proposal-class-properties',
{
loose: true
}
],
[
'#babel/plugin-proposal-object-rest-spread',
{
useBuiltIns: true
}
],
[
'#babel/plugin-proposal-private-methods',
{
loose: true
}
],
[
'#babel/plugin-proposal-private-property-in-object',
{
loose: true
}
],
[
'#babel/plugin-transform-runtime',
{
helpers: false
}
],
[
'#babel/plugin-transform-regenerator',
{
async: false
}
]
].filter(Boolean)
}
}
I don't use Typescript, I did add the yarn add babel-core#bridge --dev, I used transform, I also tried to change the jest version to 26.x.x, I added type="module" to my vue component... I don't know what the problem is.

How to configure Tailwind + Postcss with VueJS in Laravel InertiaJS

I am new to setting up the tailwind/postcss configuration using Intertia.js/Vue.js and would appreciate some guidance with my configuration files!
My goal is to be able to write postcss/scss style within my vue components, with the ability to use the postcss #apply functionality for example, like so:
Navigation.vue:
<style lang="postcss">
.nav-items {
#apply bg-red;
}
</style>
With the current configuration setup I have, I am not getting any errors compiling however the style is not being applied, it doesn't appear in the Styles in console for the element.
webpack.mix.js
const mix = require('laravel-mix')
const path = require('path')
const purgecss = require('#fullhuman/postcss-purgecss')
const tailwindcss = require('tailwindcss')
mix.js('resources/js/app.js', 'public/js')
.postCss('resources/css/app.css', 'public/css/app.css')
.options({
postCss: [
tailwindcss('tailwind.config.js'),
...mix.inProduction() ? [
purgecss({
content: ['./resources/views/**/*.blade.php', './resources/js/**/*.vue'],
defaultExtractor: content => content.match(/[\w-/:.]+(?<!:)/g) || [],
whitelistPatternsChildren: [/nprogress/],
}),
] : [],
],
})
.webpackConfig({
output: { chunkFilename: 'js/[name].js?id=[chunkhash]' },
resolve: {
alias: {
vue$: 'vue/dist/vue.runtime.js',
'#': path.resolve('resources/js'),
ziggy: path.resolve('vendor/tightenco/ziggy/src/js/route.js'),
},
},
module: {
rules: [
{
test: /\.postcss$/,
loaders: [
"style-loader",
{
loader: "css-loader",
options: { modules: true, importLoaders: 1 }
},
"postcss-loader",
]
}
]
}
})
.version()
.sourceMaps()
tailwind.config.js:
const defaultTheme = require('tailwindcss/defaultTheme')
module.exports = {
purge: [
'./resources/views/**/*.blade.php',
'./resources/css/**/*.css',
],
sourceMap: false,
theme: {
//...
},
plugins: [],
}
postcss.config.js:
module.exports = {
plugins: [
require('postcss-import'),
require('tailwindcss'),
require('autoprefixer'),
],
};
package.json:
{
//...
"devDependencies": {
"#babel/preset-env": "^7.9.6",
"#tailwindcss/custom-forms": "^0.2.1",
"axios": "^0.19",
"cross-env": "^7.0",
"css-loader": "^3.5.3",
"laravel-mix": "^5.0.1",
"laravel-mix-tailwind": "^0.1.0",
"lodash": "^4.17.13",
"postcss-css-variables": "^0.17.0",
"postcss-loader": "^3.0.0",
"postcss-nesting": "^7.0.1",
"resolve-url-loader": "^3.1.0",
"sass": "^1.15.2",
"sass-loader": "^8.0.0",
"style-loader": "^1.2.1",
"tailwindcss": "^1.4",
"vue-svgicon": "^3.2.6",
"vue-template-compiler": "^2.6.11"
},
"dependencies": {
"#babel/plugin-syntax-dynamic-import": "^7.8.3",
"#inertiajs/inertia": "^0.1.9",
"#inertiajs/inertia-vue": "^0.1.4",
"alpinejs": "^2.3.5",
"popper.js": "^1.16.1",
"portal-vue": "^2.1.7",
"postcss-import": "^12.0.1",
"postcss-nested": "^4.2.1",
"postcss-nested-ancestors": "^2.0.0",
"vue": "^2.6.11",
"vue-i18n": "^8.17.7",
"vue-meta": "^2.3.3"
}
}
Add this to webpack.config.js :
module: {
rules: [
{
test: /\.(postcss)$/,
use: [
'vue-style-loader',
{ loader: 'css-loader', options: { importLoaders: 1 } },
'postcss-loader'
]
}
],
},
Found here https://github.com/JeffreyWay/laravel-mix/issues/2211#issuecomment-546123921

use async \ await in vue?

I want to use async \ await in Vue.
there is order-list.vue, in short methods this is:
getOrder: function () {
return new Promise(function (resolve, reject) {
setTimeout(() => {
console.log('hello world');
resolve(true)
}, 2000)
});
},
example: async() => {
console.log('start');
for (let i in this.orders) {
await this.getOrder().then(
console.log('loaded ' + i)
)
}
console.log('finish');
}
it's all going to webpack.
When I start webpack, I get this message
ERROR in ./erp/vue/order-list.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib!./node_modules/vue-loader/lib??vue-loader-options!./erp/vue/order-list.vue?vue&type=script&lang=js&)
Module not found: Error: Can't resolve '#babel/runtime/regenerator' in '/Users/pankovalxndr/Sites/mysite/erp/vue'
# ./erp/vue/order-list.vue?vue&type=script&lang=js& (./node_modules/babel-loader/lib!./node_modules/vue-loader/lib??vue-loader-options!./erp/vue/order-list.vue?vue&type=script&lang=js&) 1:0-61 141:13-32 146:28-47 156:21-40
package.json
What is wrong here?
"devDependencies": {
"#babel/core": "^7.4.3",
"#babel/plugin-transform-runtime": "^7.6.2",
"#babel/preset-env": "^7.4.3",
"autoprefixer": "^8.6.5",
"babel-loader": "^8.0.0-beta.6",
"babel-runtime": "^6.26.0",
"gulp": "git://github.com/gulpjs/gulp.git#6d71a658c61edb3090221579d8f97dbe086ba2ed",
"gulp-cheerio": "^0.6.3",
"gulp-cssnano": "^2.1.2",
"gulp-postcss": "^7.0.1",
"gulp-print": "^5.0.2",
"gulp-rename": "^1.4.0",
"gulp-replace": "^0.6.1",
"gulp-sass": "^3.1.0",
"gulp-svg-sprite": "^1.5.0",
"gulp-svgmin": "^1.2.4",
"gulp-uglify": "^3.0.2",
"gulp-watch": "^5.0.1",
"vue-loader": "^15.7.2",
"vue-style-loader": "^4.1.2",
"vue-template-compiler": "^2.5.17",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.9.0"
}
My .babelrc
What is wrong here?
{
"presets": [
"#babel/preset-env"
],
"plugins": [
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
}
webpack file
What is wrong here?
module: {
rules: [
{
test: /\.vue$/,
use: 'vue-loader'
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
]
}, {
test: /\.js$/,
use: 'babel-loader'
}
]
},
plugins: [
new VueLoaderPlugin(),
]
If I remove functions with await then everything starts to work well, those things are not specifically, more precisely in some module

Type error during importing vue-formio to my vue template

I have a problem with importing vue-formio to my vue component.
Can't import FormBuilder without errors :(
After:
import { FormBuilder } from 'vue-formio';
I see in the console:
TypeError: Object prototype may only be an Object or null: undefined
Whole error You can see here: see print screen
TypeError: Object prototype may only be an Object or null: undefined
Main import:
if (document.body.classList.contains("hr:controller-requisition:action-edit")) {
require.ensure([], () => {
require("./views/requisition/edit.es6.js").default;
});
}
My formio.es6.js file:
import Vue from "vue";
import formio from "./show.vue";
import { store } from "HRComponets/store/store.es6";
export default new Vue({
el: "#formio-show",
data: {},
store,
render(h) {
return h(formio);
}
});
My vue component file:
Hi Guys, need help with vue-formio
<script>
import { FormBuilder } from 'vue-formio';
export default {
name: "formioShow",
data() {
return {
schema: {},
}
},
components: {
FormBuilder
},
};
</script>
My package.json file:
{
"name": "core",
"version": "1.0.0",
"description": "ortal",
"main": "index.js",
"directories": {
"test": "tests"
},
"scripts": {
"start": "npm run dev",
"prod": "webpack --config webpack.prod.js",
"dev": "webpack --watch --progress --config webpack.dev.js",
},
"nyc": {
"include": [
"src/**/*.(js|vue)"
],
"instrument": false,
"sourceMap": false
},
"keywords": [
"HR",
"Syrveys"
],
"browserslist": [
"> 2%",
"last 3 versions",
"not ie <= 8"
],
"devDependencies": {
"#vue/test-utils": "^1.0.0-beta.18",
"axios": "^0.18.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"clean-webpack-plugin": "^0.1.19",
"css-loader": "^0.28.11",
"eslint": "^4.19.1",
"expect": "^23.1.0",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"husky": "^1.0.0-rc.8",
"istanbul-instrumenter-loader": "^3.0.1",
"jsdom": "^11.11.0",
"jsdom-global": "^3.0.2",
"less": "^3.0.4",
"less-loader": "^4.1.0",
"mini-css-extract-plugin": "^0.4.0",
"mocha": "^5.2.0",
"mocha-webpack": "^2.0.0-beta.0",
"node-sass": "^4.9.0",
"nyc": "^11.8.0",
"prettier-eslint": "^8.8.1",
"sass-loader": "^7.0.1",
"style-loader": "^0.21.0",
"ts-loader": "^5.1.0",
"typescript": "^3.0.3",
"vue": "^2.5.16",
"vue-loader": "^15.0.10",
"vue-template-compiler": "^2.5.16",
"watchfile-webpack-plugin": "0.0.4",
"webpack": "^4.8.1",
"webpack-cli": "^2.1.3",
"webpack-dev-server": "^3.1.4",
"webpack-merge": "^4.1.2",
"webpack-notifier": "^1.6.0"
},
"dependencies": {
"amcharts3": "github:amcharts/amcharts3",
"eslint-plugin-vue": "^4.7.1",
"formiojs": "^3.5.1",
"jquery": "^3.3.1",
"lodash": "^4.17.10",
"moment-timezone": "^0.5.17",
"npm": "^6.4.1",
"numeral": "^2.0.6",
"vee-validate": "^2.1.0-beta.8",
"vue-formio": "^3.0.0",
"vue-moment": "^4.0.0-0",
"vue-multiselect": "^2.1.0",
"vue-numerals": "0.0.2",
"vue-pdf": "^3.3.1",
"vue-upload-component": "^2.8.9",
"vue-wysiwyg": "^1.7.2",
"vue2-dropzone": "^3.2.2",
"vuelidate": "^0.7.4",
"vuenut": "^0.2.2",
"vuex": "^3.0.1",
"webpack-node-externals": "^1.7.2"
}
}
My webpack config file:
const webpack = require("webpack");
const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
const HTMLWebpackPlugin = require("html-webpack-plugin");
const config = {
entry: {
core: "./src/AppBundle/VueComponents/main.es6.js",
hr: "./src/HRBundle/VueComponents/main.es6.js",
pm: "./src/PerformanceManagementBundle/VueComponents/main.es6.js"
},
output: {
filename: "[name]-app.js",
path: __dirname + "/web/assets/core/js/",
hotUpdateChunkFilename: "../webpack-hot-reload/hot-update.js",
hotUpdateMainFilename: "../webpack-hot-reload/Updatehot-update.json",
publicPath: "/assets/core/js/"
},
watchOptions: {
aggregateTimeout: 300,
poll: 1000,
ignored: /node_modules/
},
module: {
rules: [
{
test: /\.vue$/,
loader: "vue-loader"
},
{
test: /\.ts$/,
exclude: /node_modules|vue\/src/,
loader: "ts-loader",
options: {
appendTsSuffixTo: [/\.vue$/]
}
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /.scss$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.less$/,
use: ["vue-style-loader", "css-loader", "less-loader"]
},
{
test: /\.es6.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: "babel-loader"
}
}
]
},
plugins: [
new VueLoaderPlugin(),
new HTMLWebpackPlugin(),
new webpack.HotModuleReplacementPlugin(),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
],
externals: {
jquery: "jQuery"
},
resolve: {
alias: {
vue: "vue/dist/vue.js",
HRComponets: path.resolve(__dirname, "./src/HRBundle/VueComponents")
},
extensions: ["*", ".js", ".vue", ".json", ".ts"]
}
};
module.exports = config;

jest.mock() not mocking module in Babel 7 and React-Native 0.56

Like MANY others, I'm trying to upgrade my RN app to React-Native 0.56 and Babel is making everything so easy! (Not the sarcasm here) I could update RN, React to the latest and make my app compile and work, but the tests (jest) are not working anymore.
But not all the test. I manage to solve almost all the different kinds of issue, expect this one:
meeting actions › creates CLEAR_CURRENT_ATTACHMENTS when clearning current attachments
TypeError: eventActions.refreshEvents.mockImplementation is not a function
90 |
91 | beforeEach(() => {
> 92 | eventActions.refreshEvents.mockImplementation(() => ({ type: DUMMY_TYPE }));
| ^
93 | MockDate.set(A_DATE);
94 | store = mockStore({
95 | authentication: {
at Object.<anonymous> (src/calendar/actions/__tests__/meetingActions-test.js:92:32)
Test file with the test failing (Remove all the others test to simplify the example)
import moment from 'moment';
import MockDate from 'mockdate';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import getToken from 'authentication/selectors/tokenSelector';
import * as actions from '../meetingActions';
import * as eventActions from '../eventActions';
import { getPlannerComments } from '../../selectors/scheduleModificationSelectors';
const {
CLEAR_CURRENT_ATTACHMENTS,
} = actions;
jest.mock('../eventActions.js');
jest.mock('../../../authentication/selectors/tokenSelector');
jest.mock('../../selectors/scheduleModificationSelectors');
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('meeting actions', () => {
const A_TOKEN = 'token12345';
const AN_ID = 'h1234';
const A_DATE = moment('2016-08-22T21:00:00.000Z');
const AN_MEETING_EVENT = {
start: A_DATE,
end: A_DATE,
guests: [],
newGuests: [],
newAttachments: [],
contactsToAddToGuestList: [],
groupsToAddToGuestList: [],
listsToAddToGuestList: [],
};
const AN_ACCOUNT = { id: AN_ID };
const DUMMY_TYPE = 'Dummy type';
const PLANNER_COMMENTS = {};
let store;
beforeEach(() => {
eventActions.refreshEvents.mockImplementation(() => ({ type: DUMMY_TYPE }));
MockDate.set(A_DATE);
store = mockStore({
authentication: {
token: A_TOKEN,
},
session: {
account: AN_ACCOUNT,
},
meeting: AN_MEETING_EVENT,
event: {
attendees: [],
},
});
getToken.mockImplementation(() => A_TOKEN);
getPlannerComments.mockImplementation(() => PLANNER_COMMENTS);
});
it('creates CLEAR_CURRENT_ATTACHMENTS when clearing current info', () =>
store.dispatch(actions.clearCurrentInfo())
.then(() => {
expect(store.getActions()).toContainEqual({ type: CLEAR_CURRENT_ATTACHMENTS });
}));
afterEach(() => {
MockDate.reset();
});
});
I have over 800 tests that failed because of this error. From what I understood of the problem, it comes from the fact that the jest.mock
jest.mock('../domain/Attachment') // For example
is not actually mocking the class. So Attachment looks like the normal class. And so the mockImplementation of a function cause the undefined is not a function
{ [Function: Record]
iconOf: [Function: iconOf],
iconColorOf: [Function: iconColorOf],
getCleanName: [Function: getCleanName],
open: [Function: _callee2],
parse: [Function: parse] }
Package.json
{
"name": "MY APP",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest",
"ios": "react-native run-ios",
"android": "react-native run-android",
"test:watch": "npm run test -- --watch",
"lint": "eslint src --max-warnings=0",
"install-dep": "npm install && cd ios && pod install"
},
"rnpm": {
"assets": [
"./src/main/themes/fonts/assets"
]
},
"jest": {
"moduleDirectories": [
"node_modules",
"src"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
},
"preset": "react-native",
"collectCoverage": true,
"setupTestFrameworkScriptFile": "<rootDir>/setup-jasmine-env.js",
"moduleFileExtensions": [
"js",
"json",
"es6",
"ios.js",
"android.js"
],
"setupFiles": [
"./testenv.js"
],
"transformIgnorePatterns": [
"node_modules/?!(react-native)"
]
},
"dependencies": {
"bluebird": "^3.4.6",
"buffer": "^5.0.0",
"color": "^2.0.0",
"deepmerge": "^1.5.2",
"diacritics": "^1.2.3",
"immutable": "^3.8.2",
"linkify-it": "^2.0.3",
"lodash.debounce": "^4.0.8",
"moment": "^2.17.0",
"prop-types": "^15.6.0",
"react": "16.4.1",
"react-native": "0.56.0",
[...] // Lots of dependencies not related to the problem
"react-navigation": "1.5.11",
"react-redux": "^5.0.7",
"redux": "^3.7.2",
"redux-thunk": "^2.2.0",
"reselect": "^3.0.1",
"socket.io-client": "2.1.0"
},
"devDependencies": {
"#babel/core": "^7.0.0",
"babel-core": "^6.26.3",
"babel-eslint": "7.2.3",
"babel-jest": "^23.4.2",
"babel-plugin-module-resolver": "^3.1.1",
"babel-preset-react-native": "5.0.2",
"eslint": "^3.11.1",
"eslint-config-airbnb": "^13.0.0",
"eslint-import-resolver-babel-module": "5.0.0-beta.0",
"eslint-plugin-import": "^2.12.0",
"eslint-plugin-jsx-a11y": "^2.2.3",
"eslint-plugin-react": "^6.7.1",
"eslint-plugin-react-native": "^2.2.0",
"fetch-mock": "^5.1.2",
"istanbul": "0.4.5",
"jasmine-reporters": "^2.2.0",
"jest": "^23.5.0",
"jest-cli": "23.5.0",
"mockdate": "^2.0.1",
"moment-timezone": "^0.5.20",
"react-dom": "16.4.2",
"react-test-renderer": "16.4.2",
"redux-mock-store": "1.3.0",
"regenerator-runtime": "^0.12.1",
"remote-redux-devtools": "^0.5.7"
}
}
Note that like multiple issue in Jest, Babel and React-Native GitHubs, I have the Transform.
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
},
.babelrc
{
"presets": ["react-native"],
"plugins": [
[
"module-resolver",
{
"root": ["./src"],
"extensions": [".js", ".ios.js", ".android.js"]
}
]
]
}
Anyone has any idea?
If you look at the example here, you'll see that mockImplementation can only be called on a jest.fn() object. In your case, you'll need to first mock refreshEvents and then call mockImplementation on that mock:
...
eventActions.refreshEvents = jest.fn();
eventActions.refreshEvents.mockImplementation(() => ({ type: DUMMY_TYPE }));
...
If you want to keep the code you've posted as it is, then you'll have to create a subdirectory __mock__ adjacent to your mocked out module and create a file that mocks functions in that module within that subdirectory as explained here.
UPDATE:
jest.mock calls are automatically hoisted to the top of the file with the babel-jest transformer, which is what you need. Note that you are already using a jest transformer. From the docs:
If you are using the babel-jest transformer and want to use an additional code preprocessor, keep in mind that when "transform" is overwritten in any way the babel-jest is not loaded automatically anymore. If you want to use it to compile JavaScript code it has to be explicitly defined.
That means you have to explicitly include the babel-jest transform in your jest config in package.json. That should fix things.