How can I avoid app crashing because of importing jest? - javascript

I tried many ways of importing jest into my project. All of them cause my app to crash displaying the blank screen when visiting localhost:3000 even though all statements cause app to compile (the single line of import causes the app to crash):
import { mocked } from "ts-jest"
import { mocked } from '#jest/globals'
import { jest } from 'ts-jest'
import { jest } from '#jest/globals'
App crashes with the following error:
VM551:2 Uncaught ReferenceError: process is not defined
I have the following dependency in package.json:
"ts-jest": "^28.0.7"
What might be the reason behind crashing? What is the correct way to import jest? I need specifically mocked object to be available, is there a right way to make it work without crashing the app?

It sounds like you're trying to import jest or mocked into your application code that runs in the browser, which won't work. process is a global in Node, but not in the browser, which is why you're getting this error:
Uncaught ReferenceError: process is not defined
If you're trying to use mock data, you can define that data in a separate file that you can import both in your test files (which run in Node) and in your application code (which runs in the browser).

Related

Cannot import a node module inside a module web worker on the browser

1- I am trying to import a node module into my worker. I could not find a way to get it done in a straightforward manner. Many people were suggesting using things like webpack or external libraries. Why can't I simply import the node module like a regular js module import like so?
import blazeface from '#tensorflow-models/blazeface';
meanwhile, I can import other modules I created like
import getDetectedFace from "./detectFace.js";
When this error occurs I do not see any output to the console that an error has occurred. I can only tell because my worker does nothing when I try this type of import. Is this normal?

Uncaught SyntaxError: Cannot use import statement outside a module Vue 3 PWA Workbox

I am trying to convert my vue js app into a PWA. Following the workbox documentation in the following link:
https://developers.google.com/web/tools/workbox/modules/workbox-strategies
I have to import some modules
import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
import { Queue } from 'workbox-background-sync';
After running npm run build, vue js automatically generates the following line of code which is at the top of service-worker.js file followed by the imports mentioned above:
importScripts("/precache-manifest.f6666fe9d8f679ee90db8a98ef900aa4.js", "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");
My app is fully functional without any errors, if I remove the imports, the service worker is registered successfully. When i add the imports I am getting this error:
Uncaught SyntaxError: Cannot use import statement outside a module
Error during service worker registration: TypeError: Failed to register a ServiceWorker for scope ('http://127.0.0.1:8887/') with script ('http://127.0.0.1:8887/service-worker.js'): ServiceWorker script evaluation failed
From my research I have learned that the scripts need to be bundled using webpack or a similar service.
https://developers.google.com/web/tools/workbox/guides/using-bundlers
However since I am using the CDN to importScripts, according to my understanding it should automatically bundle as stated in the following website:
https://developers.google.com/web/tools/workbox/modules/workbox-sw
It's an either-or thing: if you have full control over your build a bundling process, then following the "Using bundlers with Workbox" guide and using the ES module import {...} from '...' syntax, but not using workbox-sw, would work.
If you don't have full control over your build process (and it sounds like you don't), then you can use workbox-sw to load the rest of Workbox. Since you already have the importScripts('/path/to/workbox-sw.js') in your service worker, using statements like workbox.routing.registerRoute() or workbox.strategies.registerRoute() in your service worker, and not putting in any import {...} from '...' statements, should just work.

How to test typescript function locally manually in React app?

sorry a rookie question, I am using react and typescript (via create-react-app) and if I have some totally non-UI javascript code (a module I am working on to work with some REST api), something along the lines like this:
src/lib/rest.tsx
export const getUser = async function (
username: string,
) {
let response = await fetch(`http://localhost:3000/api/auth/`, {
username
});
return response;
};
I am wondering how can I test this function locally in a REPL or browsers's dev tools, before putting it into real use. I think I have two difficulties right now:
webpack seems not even packaing this module into the code now, if I open Chrom's dev tools I can see other tsx files but not this one, simply becasue I am not importing this module anywhere I think.
even if it is packaged I dont know how to import this module in a REPL or the dev tool console because first I dont know what is the correct syntax here, Would it be import src/lib/rest.tsx? Also seems I cannot import any module in a REPL because import can only happen inside a module.
The workflow here is just I have written some simple typescript function and I want to run them in a REPL like enviorment so I can make sure they are working before using it anywhere or starting to write unit/integration tests against them.
Thanks!
1 is correct, your new module is not imported and thus not bundled by webpack.
I don't think you could use import syntax in console atm. But there are 2 ways you could try.
Just import your code in one of the bundled file, if you are using dev server, change will be reflected to browser automatically:
import { getUser } from '../../lib/rest';
getUser().then(console.log);
Or attach it to window so you could play with it in console:
import { getUser } from '../../lib/rest';
if (typeof window !== 'undefined') {
window.getUser = getUser;
}

Jest: Error when trying to import Native Modules; unable to prevent with Mock

I've recently been brought on to a team as Test Engineer and I'm trying to get Jest unit tests up and running on our React Native app. My predecessor has already authored dozens of unit tests, most of which are not running successfully.
I'm getting the following error when running npm test
FAIL __tests__/index.test.js
● Test suite failed to run
TypeError: Cannot read property '_addDeviceToGroup' of undefined
4 | } from 'react-native';
5 | const {
> 6 | _addDeviceToGroup,
| ^
7 | } = NativeModules._BleAssociator
8 | const {
9 | _queryName,
at Object._addDeviceToGroup (app/utils/mesh.js:6:3)
at Object.<anonymous> (app/actions/hierarchy.js:26:1)
at Object.<anonymous> (app/actions/organizations.js:14:1)
It seems as though the issue arose when we implemented custom Native Modules written by our backend team (again, before my joining the team).
After some research, I decided to proceed under the assumption that this has to do with Jest's inability to parse the Objective-C in the Engine that's feeding in the Native Modules and not some issue with our stack (happy to consider that possibility, though).
I've reviewed the Jest documentation, combing specifically through a couple relevant documents (Mock Functions, Using Jest with ES Module Imports, Testing Native Modules with Jest Mock, React Native Modules Guide)
My issue appears to be identical to this issue; however, the fix is not working for me. Even when mocking the NativeModules, I get the same error.
I've become familiar with the notion that Jest mocks are hoisted above the import statements, but it's not clear to me why the mocks are in the describe block in the issue I linked above (other than maybe to reset the mock function for each new test in case so as to not confound the .mock property's return data... I digress).
To me, it seems the error is occurring during the imports, before any of the code is executed. To test this, I've gone back and forth, commenting out everything but the import statements and the mocks. Doing this, I still get the same error. This is also the case when I use a beforeEach() mocha statement, as in the solution to the issue linked above.
The only thing that fixes this error commenting out the imports altogether.
I have not tried error handling (try/catch), as I'm not certain how I could still successfully import the component I'm testing if the catch block is executed.
Sorry for all that background. I have spent a couple workdays on this, so I want to make certain all my bases are covered.
Here's an example test:
/__tests__/app/components/Onboarding/Splash/Splash.test.js
import {
NativeModules,
} from 'react-native';
import { Splash } from '../../../../../app/components/Onboarding/Splash/Splash.js';
// import login from '../../../../../app/actions/login';
// NativeModules._BleAssociator._addDeviceToGroup = jest.fn();
// login = jest.fn;
export default function({React, shallow}) {
const props = {
// some test props
};
function make({navigation, getUserInfo, verifyUser, login} = props) {
return shallow(
// renders the component with props
);
}
describe('<Splash />', () => {
// I added this part (didn't help)
beforeEach(() => {
NativeModules._BleAssociator._addDeviceToGroup = jest.fn();
login = jest.fn;
});
// end part I added
// stuff (all the tests are in here)
});
}
The NativeModules and login imports, the commented out lines, and the beforeEach() block are things I've tried intermittently to no avail.
When trying to trace this error, I found that commenting out import statement in the original Splash.js that run scripts (as ES6 import runs the script it references) that try to import NativeModules fixes the error I see. As you might have gleaned from the stack trace, these go many levels deep.
PHEW. If you've read this far, I really appreciate the help.
Sorry to have such a long and complicated question. As you can see, we have a large and convoluted stack. It's possible the fix from the issue above isn't working because of how many chained imports happen before getting to the error.
I'd love it if it's a tiny fix that I'm missing or if there was some sort of "shallow"-ish import that I'm not aware of.
Thanks a bajillion for your help. Any input is welcome.
I found the solution to this. I had been worried that perhaps the mocks weren't being tracked through all the import statement. What was really happening was I was formatting the mocks wrong.
I did not see this in the standard Jest documentation, but instead found it here.
Adding this to my *.test.js files worked:
import { NativeModules } from 'react-native';
jest.mock('NativeModules', () => {
return {
_BleAssociator: {
_addDeviceToGroup: jest.fn()
},
// ... and so on for all the other methods expected in NodeModules
};
});
Just for posterity's sake, I think this would be best kept in its own script and imported into the tests... I haven't tried this yet.

Using Vue Design System in Nuxt is throwing errors about export in system.js

I am trying to get the components imported into a Nuxt project, following the steps here:
https://github.com/viljamis/vue-design-system/wiki/getting-started#using-design-system-as-an-npm-module
Nuxt does not have a main.js (everything is plugin based), so what I have done is create a "plugin" and then do the import code in there like so (Nuxt recommends this for other libraries too and works fine):
vue-design-system.js
import Vue from 'vue'
import system from 'fp-design-system'
import 'fp-design-system/dist/system/system.css'
Vue.use(system)
Then in my config I do (removed other code in config):
nuxt.config.js
module.exports = {
css: [
{ src: 'fp-design-system/dist/system/system.css', lang: 'css' }
],
plugins: [
{ src: '~plugins/vue-design-system', ssr: true }
]
}
When I run npm run dev in my theme, it builds, but I get a warning:
WARNING Compiled with 1 warnings warning in
./plugins/vue-design-system.js 7:8-14 "export 'default' (imported as
'system') was not found in 'fp-design-system'
Seems to have an issue with the generated system.js regarding the export (the command npm run build:system).
In my page on screen I get the following error when trying to use a component in the design system:
NuxtServerError Cannot find module
'fp-design-system/src/elements/TextStyle' from
'/Users/paranoidandroid/Documents/websites/Nuxt-SSR'
If I hard refresh the page, I then get another message:
NuxtServerError render function or template not defined in component:
anonymous
Any idea what's happening here? It would be really great to get this working somehow.
At this current time, I'm not sure if it's a Nuxt issue or a Vue Design System issue. I think the latter, just because the Nuxt setup I have right now is very bare-bones...so it's not something else causing this.
Thanks.
Repository on GitHub:
Here is the repo for my "theme", but in order to get this going, you will need to create a design system separate from this with the same name and follow the steps to use the design system as a local (file) NPM module.
https://github.com/michaelpumo/Nuxt-SSR
console.log of system (from the JS import statement)
As for your first error (""export 'default' (imported as 'system') was not found in 'fp-design-system'"), the UMD built JS from vue-design-system does not export a "default" object. But you can simply workaround the issue by importing it as:
import * as system from 'fp-design-system'
instead of:
import system from 'fp-design-system'
Then another issue comes quickly as you noticed in your comments: "window is not defined", due again to the UMD built JS that expects window to be globally available, instead of the usual trick to use this (which equals window in a browser). Therefore as it is, the build is not comptible with SSR.
You could however slightly rework the built JS by replacing the first occurrence of window by this, but I am not sure if the result will still work.
Most probably you should better keep this module for client rendering only.
It seems Vue is looking for the ES6 pattern for importing module, which you should use for external javascript modules/files.
in ES6 it is
export default myModule
in ES5 it was
module.exports = myModule
Hope it will help.

Categories

Resources