Cannot read property 'LEENDPOINT' of undefined - reactjs

I am integrating LogEntries in my react application.
But right after importing LogEntry js file. I am getting console error that:
const Logger = require ('./logger.jsx')('your token', {trace: true});
Error:
le.min.js:5 Uncaught TypeError: Cannot read property 'LEENDPOINT' of undefined
at new e (le.min.js:5)
at new p (le.min.js:10)
at f (le.min.js:11)
at Object.init (le.min.js:12)
at module.exports (logger.jsx:9)
at Object.defineProperty.value (App.js:10)
at __webpack_require__ (bootstrap 9c287bdecc8b4481a87b:19)
at Object.defineProperty.value (AppWrapper.js:2)
at __webpack_require__ (bootstrap 9c287bdecc8b4481a87b:19)
at Object.<anonymous> (index.js:8)
Update:
After debbuging I came to know that window object is undefined in logger file.
This is piece of code which is causing havoc:
if (window.LEENDPOINT) {
_endpoint = window.LEENDPOINT;
}
Still looking for solution.
Update 2.0:
Here is my Logger.jsx
const LogEntries = require ('./le.min.js');
module.exports = (token, opts={}) => {
if(!token){
throw new Error ('A valid token is required for all LogEntries library implementations.');
}
opts.token = token;
LogEntries.init(opts);
return LogEntries;
}

Following solution worked for me:
Downloaded le.min.js from https://docs.logentries.com/docs/javascript
Imported <script src="/assets/scripts/le.min.js"></script> in my index.html. Make sure you import it before bundle.js
Created one file. Logger.js
const token = 'token';
const region = 'us';
const trace = true;
/*eslint-disable */
LE.init({ token, region, trace});
export default LE;
/*eslint-enable */
Whenever you want to make log import import Logger from './Logger';
Log using: Logger.error('Log');

Related

Serve static javascript file from nextjs api

I need a route in website build with nextjs that sends javascript that can be used on different website to do some things.
I created new file in pages/api, let's call it sendTest.ts so it's location is pages/api/sendTest.ts. In the same folder I crated test.ts file that I want to send from sendTest.ts.
sendTest.ts
import type { NextApiRequest, NextApiResponse } from 'next'
import fs from 'fs';
import path from 'path'
const filePath = path.join(__dirname, 'test.js');
const file = fs.readFileSync(filePath);
export default function handler(
req: NextApiRequest,
res: NextApiResponse
) {
res.setHeader('Content-Type', 'text/javascript');
res.status(200).send(file)
}
test.ts
console.log('hello');
After build nextjs serves that file at website.com/api/sendTest but after bundling it ends up as
"use strict";
(() => {
var exports = {};
exports.id = 318;
exports.ids = [318];
exports.modules = {
/***/ 211:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
__webpack_require__.r(__webpack_exports__);
console.log("hello there");
/***/ })
};
;
// load runtime
var __webpack_require__ = require("../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = (__webpack_exec__(211));
module.exports = __webpack_exports__;
})();
which when used in different page as
<script src="website.com/api/sendTest"></script>
results in error
Uncaught ReferenceError: require is not defined
at sendTest:22:27
at sendTest:28:3
My question is how can I force nextjs to skip loading webpack into that file and just allow typescript to change content into javascript and serve file as is? Or is there better way to do what I want, which is sending javascript from specified nextjs route?
Got it.
I changed
const filePath = path.join(__dirname, 'test.js');
to
const filePath = path.resolve('.', 'script/test.js');
and put my script file into folder called script (name doesn't matter) in the main directory

Mobx React - CreateViewModel - Error - Object is not a function

I am trying to use the createViewModel from mobx-utils in a Mobx/React app.
My Store is:
export class CompanyStore extends StoreExt {
#observable
companyDetails: ICompanyDetails = {}
}
And when i use the 'createViewModel' function, in the component like so:
function CompanyDetails() {
const { companyStore } = useRootStore()
const test = createViewModel(companyStore.companyDetails);
}
I getting this error:
Uncaught TypeError: Object(...) is not a function
at new ViewModel (mobx-utils.module.js?1a9d:629)
at createViewModel (mobx-utils.module.js?1a9d:775)
at CompanyDetails (index.tsx?dbb5:21)
at eval (observer.js?796d:24)
at eval (useObserver.js?338c:91)
at trackDerivedFunction (mobx.es6.js?cacc:668)
at Reaction.track (mobx.es6.js?cacc:1705)
at eval (useObserver.js?338c:89)
at useQueuedForceUpdateBlock (useQueuedForceUpdate.js?20c5:19)
at useObserver (useObserver.js?338c:83)
What could the cause be?
Well, The issue was an incompatibility between Mobx and mobx-utils packages. By matching them to the same version, the issue was solved.

NextJs + amcharts : production build error : ReferenceError: addEventListener is not defined

I am working on nextjs project and using amcharts library.
When I build production build, it gives me below error.
> Build error occurred
{ ReferenceError: addEventListener is not defined
at new Registry (D:\XKDashboardClient\.next\server\static\FsJlbi7eD-pYXPY5IEwnp\pages\patientDetails.js:4945:9)
at Module.u55L (D:\XKDashboardClient\.next\server\static\FsJlbi7eD-pYXPY5IEwnp\pages\patientDetails.js:5159:16)
at __webpack_require__ (D:\XKDashboardClient\.next\server\static\FsJlbi7eD-pYXPY5IEwnp\pages\patientDetails.js:29:31)
at Object.11 (D:\XKDashboardClient\.next\server\static\FsJlbi7eD-pYXPY5IEwnp\pages\patientDetails.js:334:18)
at __webpack_require__ (D:\XKDashboardClient\.next\server\static\FsJlbi7eD-pYXPY5IEwnp\pages\patientDetails.js:29:31)
at D:\XKDashboardClient\.next\server\static\FsJlbi7eD-pYXPY5IEwnp\pages\patientDetails.js:124:18
at Object.<anonymous> (D:\XKDashboardClient\.next\server\static\FsJlbi7eD-pYXPY5IEwnp\pages\patientDetails.js:127:10)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32) type: 'ReferenceError' }
Automatically optimizing pages .npm ERR! code ELIFECYCLE
Here is my next.config.js file
const withCSS = require("#zeit/next-css");
const withImages = require("next-images");
const withFonts = require("nextjs-fonts");
const withTM = require("next-transpile-modules")([
"react-native-vector-icons",
"#amcharts/amcharts4/core",
"#amcharts/amcharts4/charts",
"#amcharts/amcharts4/themes/animated",
]); // pass the modules you would like to see transpiled
module.exports = withCSS(
withTM(
withImages(
withFonts({
/* config options here */
env: {
API_URL: "http://localhost:4000/api/",
SOCKET_URL: "http://localhost:4000/",
},
})
)
)
);
If I comment out below code then it works and no error.
this code is from - node_modules#amcharts\amcharts4.internal\core\Registry.js
UPDATE
I fixed the build error by removing amcharts from webpack file. and import it like below when page loads.
let am4core = null;
let am4charts = null;
let am4themesAnimated = null;
if (process.browser) {
console.log("process.browser", process.browser);
am4core = require("#amcharts/amcharts4/core");
am4charts = require("#amcharts/amcharts4/charts");
am4themesAnimated = require("#amcharts/amcharts4/themes/animated");
am4core.useTheme(am4themesAnimated.default);
}
Now my prod build works fine and chart is loading fine on first load.
When I refresh the page it shows me below error:
charts.js:1 Uncaught ReferenceError: am4internal_webpackJsonp is not defined
at charts.js:1
(anonymous) # charts.js:1
maps.js:1 Uncaught ReferenceError: am4internal_webpackJsonp is not defined
at maps.js:1

Apollo - React (Typescript) Invariant Error when building production build

I am creating a new react app with gatsby, typescript, and apollo (for graphql queries).
When testing in dev, the app compiles and runs with no errors thrown.
When I transpile the build, using 'gatsby build', it fails with an error.
I don't understand why or where this is being triggered. It seems to be something to do with the way webpack is checking as it's building, but I don't know how to pinpoint the issue and there doesn't seem to be any material out there with a clear answer for me.
It seems to be caused by the httplink module. The code that triggers the error when present in any .tsx file is:
import { HttpLink } from 'apollo-link-http'
const link = new HttpLink({
uri: 'http://localhost:3001/graphql'
})
The error shown is the following:
error Building static HTML failed
See our docs page on debugging HTML builds for help https://gatsby.dev/debug-html
10 | function InvariantError(message) {
11 | if (message === void 0) { message = genericMessage; }
> 12 | var _this = _super.call(this, typeof message === "number"
| ^
13 | ? genericMessage + ": " + message + " (see https://github.com/apollographql/invariant-packages)"
14 | : message) || this;
15 | _this.framesToPop = 1;
WebpackError: Invariant Violation: Invariant Violation: 1 (see https://github.com/apollographql/invariant-packages)
- invariant.esm.js:12 new InvariantError
[lib]/[apollo-link-http-common]/[ts-invariant]/lib/invariant.esm.js:12:1
- bundle.esm.js:64 checkFetcher
[lib]/[apollo-link-http-common]/lib/bundle.esm.js:64:52
- bundle.esm.js:8 createHttpLink
[lib]/[apollo-link-http]/lib/bundle.esm.js:8:17
- bundle.esm.js:139 new HttpLink
[lib]/[apollo-link-http]/lib/bundle.esm.js:139:1
- Strategy.tsx:6 Module../src/components/Strategy.tsx
lib/src/components/Strategy.tsx:6:14
- bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1
- bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1
- sync-requires.js:10 Object../.cache/sync-requires.js
lib/.cache/sync-requires.js:10:56
- bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1
- static-entry.js:9 Module../.cache/static-entry.js
lib/.cache/static-entry.js:9:22
- bootstrap:19 __webpack_require__
lib/webpack/bootstrap:19:1
- bootstrap:83
lib/webpack/bootstrap:83:1
- universalModuleDefinition:3 webpackUniversalModuleDefinition
lib/webpack/universalModuleDefinition:3:1
- universalModuleDefinition:10 Object.<anonymous>
lib/webpack/universalModuleDefinition:10:2"
Is this typescript issue, gatsby issue, apollo issue, or a webpack issue? Or a combination?
Thank you for any help you can give! I'm struggling with my understanding of all the pieces here.
I understand that Invariant Violations are about an issue with the wrong types being referenced. Because this occurs in the module, I'm not sure if I'm doing something wrong, or if it's an issue inside the imported library. Maybe it's an issue that I'm forcing typescript checks on a basic javascript based library. I still didn't quite come to a conclusion on this.
I tried adding the following config to gatsby-node.js to ignore the module checks (as suggested here: https://gatsby.dev/debug-html), with no successful build, though the error did change, as it could not see the module.
exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
if (stage === "build-html") {
actions.setWebpackConfig({
module: {
rules: [
{
test: /apollo-link-http/,
use: loaders.null(),
},
],
},
})
}
}
To recap, this is the code designed to create the client object to enable queries to the graphql endpoint. When running 'gatsby build' the in variant error occurs (see above).
import * as React from 'react'
import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { HttpLink } from 'apollo-link-http'
const cache = new InMemoryCache()
const link = new HttpLink({
uri: 'http://localhost:3001/graphql'
})
const client = new ApolloClient({
cache,
link
})
I'm a newbie at this. After hours of looking I finally tracked down the error in the file. On closer inspection, when the environment is production (process.env.NODE_ENV === "production"), then the error is not detailed. So I looked at what the error would be if the environment was something else, and changed the file to output this to the console. What I got back was:
fetch is not found globally and no fetcher passed, to fix pass a fetch for
your environment like https://www.npmjs.com/package/node-fetch.
For example:
import fetch from 'node-fetch';
import { createHttpLink } from 'apollo-link-http';
const link = createHttpLink({ uri: '/graphql', fetch: fetch });
I added fetch to my code, and it built a production version with no errors.
I don't understand why this error was not thrown with the dev environment, but I guess it's something to do with the lazy loading.
Problem fixed.

TypeError from screenfull library during jest test

I've added screenfull, a wrapper for the Fullscreen API (https://github.com/sindresorhus/screenfull.js) to a Redux-connected React component. The application uses Typescript elsewhere, but not in the components. Screenfull is used as follows in the component:
componentDidUnmount() {
screenfull.on('change', () => this.props.toggleFullscreen());
}
componentWillUnmount() {
screenfull.off('change', () => this.props.toggleFullscreen());
}
and I have a test as follows (there are more failing in the component test file, but I thought I'd share the first one)
it('mounts with initial state', () => {
const store = configureStore(reducer);
const container = mount(
<Provider store={store}>
<VideoBoundingBoxApp inIframe={false} />
</Provider>);
expect(container.find('VideoBoundingBoxApp')).toExist();
});
The application runs and works as expected, but when running yarn test, I get the following error:
console.error node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/virtual-console.js:29
Error: Uncaught [TypeError: _screenfull2.default.on is not a function]
at reportException (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:66:24)
at invokeEventListeners (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:209:9)
at HTMLUnknownElementImpl._dispatch (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:119:9)
at HTMLUnknownElementImpl.dispatchEvent (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:82:17)
at HTMLUnknownElementImpl.dispatchEvent (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/nodes/HTMLElement-impl.js:30:27)
at HTMLUnknownElement.dispatchEvent (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:157:21)
at Object.invokeGuardedCallbackDev (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:944:16)
at invokeGuardedCallback (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:993:29)
at commitRoot (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7157:9)
at completeRoot (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8065:36) TypeError: _screenfull2.default.on is not a function
at VideoBoundingBoxApp.componentDidMount (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/src/components/VideoBoundingBox/VideoBoundingBoxApp.jsx:122:28)
at commitLifeCycles (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:5347:26)
at commitAllLifeCycles (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7018:9)
at HTMLUnknownElement.callCallback (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:906:14)
at invokeEventListeners (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:193:27)
at HTMLUnknownElementImpl._dispatch (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:119:9)
at HTMLUnknownElementImpl.dispatchEvent (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:82:17)
at HTMLUnknownElementImpl.dispatchEvent (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/nodes/HTMLElement-impl.js:30:27)
at HTMLUnknownElement.dispatchEvent (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-environment-jsdom/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:157:21)
at Object.invokeGuardedCallbackDev (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:944:16)
at invokeGuardedCallback (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:993:29)
at commitRoot (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7157:9)
at completeRoot (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8065:36)
at performWorkOnRoot (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8015:11)
at performWork (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7933:9)
at performSyncWork (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7910:5)
at requestWork (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7810:7)
at scheduleWorkImpl (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7685:13)
at scheduleWork (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7645:12)
at scheduleRootUpdate (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8273:5)
at updateContainerAtExpirationTime (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8301:12)
at Object.updateContainer (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8328:14)
at Object.create (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9009:18)
at Object.<anonymous> (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/src/test/components/VideoBoundingBox/VideoBoundingBoxApp.test.jsx:42:49)
at Object.asyncFn (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-jasmine2/build/jasmine_async.js:82:37)
at resolve (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-jasmine2/build/queue_runner.js:52:12)
at new Promise (<anonymous>)
at mapper (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-jasmine2/build/queue_runner.js:39:19)
at promise.then (/Users/mschoemaker/Desktop/CrowdFlower/projects/image_annotation/node_modules/jest-jasmine2/build/queue_runner.js:73:82)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
(similar for screenfull.off...) I am not sure how to parse this. I don't think it's Typescript related. Would anyone have any idea?
I (well, mostly my boss) figured it out. Turns out, the screenfull code has a check for whether document contains methods such as requestFullscreen, otherwise it returns false. I fixed this by adding
// fullscreen library will cause an error in jest tests
// if it can't find fullscreen methods on document
[
'requestFullscreen',
'exitFullscreen',
].forEach(each => (document[each] = () => {})); // eslint-disable-line
to my setupTests.js
#Michel Schoemaker answer is correct, but I wanted to provide more context for those curious souls out there like myself. Thankfully, screenfull's source code is super short and easy to reason about.
Looking at the source, you'll see a self-invoking function right at the top which stores its return value in a variable called fn.
// This is what I'm talking about right here. See the end of this function
var fn = (function () {
var val;
var fnMap = [
[
'requestFullscreen',
'exitFullscreen',
'fullscreenElement',
'fullscreenEnabled',
'fullscreenchange',
'fullscreenerror'
],
// New WebKit
[
'webkitRequestFullscreen',
'webkitExitFullscreen',
'webkitFullscreenElement',
'webkitFullscreenEnabled',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
// Old WebKit
[
'webkitRequestFullScreen',
'webkitCancelFullScreen',
'webkitCurrentFullScreenElement',
'webkitCancelFullScreen',
'webkitfullscreenchange',
'webkitfullscreenerror'
],
[
'mozRequestFullScreen',
'mozCancelFullScreen',
'mozFullScreenElement',
'mozFullScreenEnabled',
'mozfullscreenchange',
'mozfullscreenerror'
],
[
'msRequestFullscreen',
'msExitFullscreen',
'msFullscreenElement',
'msFullscreenEnabled',
'MSFullscreenChange',
'MSFullscreenError'
]
];
var i = 0;
var l = fnMap.length;
var ret = {};
// This for loop essentially checks the current document object for the property/methods above.
for (; i < l; i++) {
val = fnMap[i];
if (val && val[1] in document) {
for (i = 0; i < val.length; i++) {
ret[fnMap[0][i]] = val[i];
}
return ret;
}
}
// If it doesn't find any of them, this whole function returns false
// and the fn variable is set to this returned value.
return false;
})();
Then further down in the you'll see for a simple conditional check on this fn variable.
// Sidenote, if you just remove the bang from the conditional, this package
// works in testing. But obviously we don't want to do that.
if (!fn) {
if (isCommonjs) {
module.exports = {isEnabled: false};
// If log out the value of screenfull after importing it
// in your test, this is what you'll see -> {isEnabled: false}
// Thus screenfull sets this object as the exported module and returns early.
} else {
window.screenfull = {isEnabled: false};
}
return;
}
So back to #Michel Schoemaker's answer; The reason that works is because we're basically monkey patching these properties/methods in the document object so Screenfull thinks we have a compatible environment. Once it think's we have a compatible environment, Jest can mock the library as usual.
I did things a little different than #Michel Schoemaker because I was only using screenfull in two methods of my application so I didn't need to set them up for my whole testing environment. Here' my approach:
thing.spec.js
import screenfull from 'screenfull';
jest.mock('screenfull');
//********* Fullscreen **********//
describe('Fullscreen', () => {
beforeEach(() => {
document.requestFullscreen = jest.fn();
document.exitFullscreen = jest.fn();
document.fullscreenElement = jest.fn();
document.fullscreenEnabled = jest.fn();
document.fullscreenchange = jest.fn();
document.fullscreenerror = jest.fn();
});
afterEach(() => {
jest.clearAllMocks();
});
test('test name', (done) => {
// Assemble
// Act
// Assert
expect(screenfull.toggle).toHaveBeenCalled();
done();
});
});
For one thing in the unit test you likely want to jest.mock this dependency.
And the _screenfull2.default.on is not a function error might be caused by mismatch between commonjs modules and es6 modules. How are you importing screenfull?

Resources