How get window values in Tests with Enzyme, Jest + Create React App - javascript

Due to the build process I'm using to push my app out I'm passing some environment variables in a file after build, which works fine. However it breaks my tests with the following error message:
TypeError: Cannot read property 'DATA' of undefined
57 | Auth: {
58 | oth,
> 59 |
| ^
60 |
61 | identity: checkEnv(window.env.DATA,
62 | process.env.REACT_APP_DATA),
I've tried many solutions but have yet to be able to mock the window.env data, how would I do so?

Create React App allows you to initialize the test environment by including a src/setupTests.js file that "will be automatically executed before running your tests".
Create React App also sets up the testing environment with jsdom which provides the global window object.
You can set window.env in src/setupTests.js and it will be available during your tests:
src/setupTests.js
window.env = {
DATA: 'hi'
}
src/code.js
export const getData = () => window.env.DATA
src/code.test.js
import { getData } from './code';
test('env', () => {
expect(getData()).toBe('hi'); // SUCCESS
})

Brian Adams's (also Bryan Adams has great songs!) answer is correct but I wanted to clarify some things. In my case, I tried multiple things but none worked, including Brian's solution. I created the src/setupTests.js file but it seemed like it was not doing anything. After spending hours I realized that I was using react version 17.0.2 and enzyme-adapter version 16.x.x. That was the reason why none of the solutions were working. After installing "#wojtekmaj/enzyme-adapter-react-17" everything started working fine. Settings inside setupTests.js file are automatically applied during the test. So if the solutions that you are trying are not working, make sure that you are using the correct versions of the packages.

Related

Problems with using #mongodb-js/charts-embed-dom to embed a chart from MongoDB

METHOD 1
I am trying to embed a chart from MongoDB using the following code, which was adapted from documentation from MongoDB and NPM.
<script src="https://unpkg.com/#mongodb-js/charts-embed-dom"></script>
<script>
const ChartsEmbedSDK = window.ChartsEmbedSDK;
const sdk = new ChartsEmbedSDK({
baseUrl: "https://charts.mongodb.com/charts-webscraping-ciaso-ercot-wnjhz",
});
const chart = sdk.createChart({
chartId: "62d7224c-79ab-41ca-83f6-690f4ab86869",
});
chart.render(document.getElementById('chart'));
</script>
</body>
The error I’m getting is “TypeError t is null”
a picture of the error
Near as I can tell that might mean that whatever is supposed to be imported from https://unpkg.com/#mongodb-js/charts-embed-dom is not coming through so the sdk and the chart aren’t getting created properly. Hence why the chart comes up null when it trys to getElementById.
METHOD 2
I also tried a different method. What you see below is directly copied from Mongo’s documentation. I got an error that “relative references must begin with /, ./, or ../”.
<script type=module> /*did that to avoid error cannot import outside a module*/
import ChartsEmbedSDK from "#mongodb-js/charts-embed-dom"; //error: relative references must begin with /, ./, or ../
//import ChartsEmbedSDK from "https://unpkg.com/#mongodb-js/charts-embed-dom" // Ambiguous indirect export: default
// import ChartsEmbedSDK from "/unpkg.com/#mongodb-js/charts-embed-dom" //error not found.
//import 'https://unpkg.com/#mongodb-js/charts-embed-dom'; // TypeError: t is null (same as other method)
const sdk = new ChartsEmbedSDK({
baseUrl: "https://charts.mongodb.com/charts-webscraping-ciaso-ercot-wnjhz",
});
const chart = sdk.createChart({
chartId: "62d7224c-79ab-41ca-83f6-690f4ab86869",
height: "700px",
// Additional options go here
});
chart.render(document.getElementById("chart"));
</script>
You can see I also tried a few other things (commented out).
I think that for method 2 a possible reason it’s not working is that I wasn’t able to install the #mongodb-js/charts-embed-dom package correctly. When I tried to install using npm this is what I saw:
screenshot of error with npm
I did some looking into this problem but was never able to resolve it.
Overall it seems like I'm not able to properly import the charts-embed-dom. It seems to me like method 1 only has one problem to fix, whereas method 2 has possibly 2 or more layers of problems, so I’m hoping there is a relatively simple solution to method 1.
I know another solution would be to use an iframe. I've gotten that to work, but it just doesn't seem to be versatile enough to do what I need (drop down boxes, dynamic filtering)

Typescript not compiling enum in symlinked folder

EDIT: Unfortunately this seems like a known issue that cannot be solved without messing with create-react-app, although I could be wrong :( https://github.com/facebook/create-react-app/issues/3547#issuecomment-593764097
I am working on a react project using typescript and firebase functions, with my firebase functions project folder inside the project folder for the react app. As there are lots of enums and interfaces that I want to keep consistent between my frontend (the react app) and my backend (the firebase functions), I use a symlink to share a folder containing files common between these two projects. This works fine with interfaces, but causes errors when I try to use an enum exported from this symlinked folder:
ERROR in ./functions/src/shared-types/roles.ts 3:0
Module parse failed: The keyword 'enum' is reserved (3:0)
File was processed with these loaders:
* ./node_modules/#pmmmwh/react-refresh-webpack-plugin/loader/index.js
* ./node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
| __webpack_require__.$Refresh$.runtime = require('/Users/joel/my-project/node_modules/react-refresh/runtime.js');
|
> enum Roles {
| Admin = 'Admin',
| Access = 'Access',
Repro
Starting from a fresh create-react-app with typescript support, add a folder called shared-types at the same level as src and put a file in it called MyEnum.ts:
// shared-types/MyEnum.ts
enum MyEnum {
Foo = "foo",
Bar = "bar"
}
export default MyEnum;
Then, make a symlink between that folder and another one also called shared-types inside src:
$ ln -s /path/to/project/shared-types /path/to/project/src/shared-types
Then, import and use MyEnum in App.tsx:
// src/App.tsx
import React from 'react';
import './App.css';
import MyEnum from "./shared-types/MyEnum";
function App() {
return (
<div className="App">
<h1>{MyEnum.Bar}</h1>
</div>
);
}
export default App;
Finally, just run npm start:
ERROR in ./shared-types/MyEnum.ts 3:0
Module parse failed: The keyword 'enum' is reserved (3:0)
File was processed with these loaders:
* ./node_modules/#pmmmwh/react-refresh-webpack-plugin/loader/index.js
* ./node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
| __webpack_require__.$Refresh$.runtime = require('/Users/joel/repro/node_modules/react-refresh/runtime.js');
|
> enum MyEnum {
| Foo = 'foo',
| Bar = 'bar',
Things that aren't causing it
It's not that typescript is ignoring the shared-types folder, as everything compiles fine if you add an interface to that folder and use it in App.tsx. Plus, running tsc --listFilesOnly will return a list including /path/to/project/src/shared-types/MyEnum.tsc.
It's not that my version of typescript doesn't support enums or that enums are disabled, as everything works fine if you add an enum to App.tsx itself.
Thanks in advance for the help! And feel free to suggest better ways of sharing files between these two projects in the comments if there are any!
It turns out that create-react-app doesn't support symlinks under src at all! The fact that the interface stuff worked at all seems to be a fluke.
https://github.com/facebook/create-react-app/issues/3547
This seems to have been a known issue for four years, but there is no blessed solution to it yet. 🫤

Getting "TypeError: Cannot convert a Symbol value to a string" on some files

I have a create-react-app with the default setting. With some of my tests, I'm getting
TypeError: Cannot convert a Symbol value to a string
2 | import * as React from 'react';
3 |
> 4 | import { SomeItem } from 'some-library';
| ^
at Object.get (node_modules/create-emotion-styled/dist/index.cjs.js:216:200)
at Proxy.toString (<anonymous>)
at Array.forEach (<anonymous>)
at Object.<anonymous> (src/components/__tests__/SampleComponent.test.tsx:4:1)
This is only happening on some of the files. This specific import import { SomeItem } from 'some-library'; is in ALL of my test files, and yet some of them pass, and some of them throw this error.
This just happens for test; building and the dev-server work just fine.
I'm very confused since this is not a consistent error and so I don't know how to debug this.
UPDATE
Seems like the problem is with react-scripts; I downgraded to v3.0.0 and re-ran test (had to run it with SKIP_PREFLIGHT_CHECK=true because of all the other modules that I have installed), and the tests passed without any issue.
I can't comment, so I can't ask you any questions before answering, sorry.
It looks like you're trying to use emotion.
In emotion v10 create-emotion-styled would not be supported, check out this issue and consider using CacheProvider instead.

Unable to import andThen in acceptance test - ember.js

I am quite new to ember.js project where i am trying to write my first acceptance test for testing my root path works. I am following the below tutorial . I was unable to import "module-for-acceptance" from the helpers as its deprecated. when i run the below test i am getting an error which says (0 , _testHelpers.andThen) is not a function. I had also gone through ember js discussion post and imported andThen. It does not seem to work . How can i import andThen and make my test work . Thank you.
Test case
import { module, test } from 'qunit';
import { visit, currentURL ,andThen } from '#ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
module('Acceptance | list rentals', function(hooks) {
setupApplicationTest(hooks);
test('should redirect to rentals route', function (assert) {
visit('/');
andThen(function() {
assert.equal(currentURL(), '/rentals', 'should redirect automatically');
});
});
});
Log
Died on test #1 at Object.<anonymous> (http://localhost:7357/assets/tests.js:8:21)
at processModule (http://localhost:7357/assets/test-support.js:3765:16)
at module$1 (http://localhost:7357/assets/test-support.js:3790:4)
at Module.callback (http://localhost:7357/assets/tests.js:6:21)
at Module.exports (http://localhost:7357/assets/vendor.js:111:32)
at requireModule (http://localhost:7357/assets/vendor.js:32:18)
at TestLoader.require (http://localhost:7357/assets/test-support.js:13736:9): (0 , _testHelpers.andThen) is not a function# 60 ms
Source:
TypeError: (0 , _testHelpers.andThen) is not a function
at Object.<anonymous> (http://localhost:7357/assets/tests.js:10:32)
at runTest (http://localhost:7357/assets/test-support.js:5618:30)
at Test.run (http://localhost:7357/assets/test-support.js:5604:6)
at http://localhost:7357/assets/test-support.js:5831:12
at processTaskQueue (http://localhost:7357/assets/test-support.js:5197:24)
at advanceTaskQueue (http://localhost:7357/assets/test-support.js:5182:4)
at Object.advance (http://localhost:7357/assets/test-support.js:5168:4)
at unblockAndAdvanceQueue (http://localhost:7357/assets/test-support.js:6944:20)
at begin (http://localhost:7357/assets/test-support.js:6978:5)
at http://localhost:7357/assets/test-support.js:6219:6
Tried to restart test while already started (test's semaphore was 0 already)# 61 ms
Source:
at resume (http://localhost:7357/assets/test-support.js:6171:5)
at done (http://localhost:7357/assets/test-support.js:6362:7)
at Class.asyncEnd (http://localhost:7357/assets/test-support.js:13822:9)
at asyncEnd (http://localhost:7357/assets/vendor.js:68040:15)
at http://localhost:7357/assets/vendor.js:67197:31
at invoke (http://localhost:7357/assets/vendor.js:65509:16)
at Queue.flush (http://localhost:7357/assets/vendor.js:65400:13)
at DeferredActionQueues.flush (http://localhost:7357/assets/vendor.js:65597:21)
Ember testing has moved to an async/await pattern instead of using andThen and other global test helpers. That tutorial is for a fairly old version of Ember, you'll have a lot more success with a more recent guide. Even if you are not ready to update to a newer version of ember I would still recommend following the new test patterns as they are significantly easier to read and write.
If you want to test it with andThen you wouldn't need to import it as it was provided as a global, but you need to make sure your testing dependencies are correct. I would start with comparing your current package.json with the default for ember apps at that time you may need to downgrade some packages in order to get access to the old imports and global test helpers.

Preact Compat incompatibility in Jest tests

I'm using preact 8.4.2 and have preact-compat as well.
I'm using linkifyjs/react to render links in text. This works fine in development, but my tests are failing when trying to import the React-dependent `linkifyjs/react' library with this error:
● Test suite failed to run
TypeError: Cannot redefine property: type
at Function.defineProperty (<anonymous>)
1 | import {h, Component, createRef} from 'preact';
> 2 | import Linkify from 'linkifyjs/react';
| ^
I'm really not sure what this error means, and I'm confused because preact-compat is supposed to allow use of libraries with React dependencies. The stack trace points to preact-compat/src/index.js:60 which has:
Object.defineProperty(VNode.prototype, 'type', {
get() {
return this.nodeName;
},
set(v) {
this.nodeName = v;
},
configurable: true
});
I ran into the same issue. What caused the problem for me was that both preact-compat and enzyme-adapter-preact-pure were trying to make a Preact vNode to look like a React element.
https://github.com/preactjs/enzyme-adapter-preact-pure/pull/62
This pull request for enzyme-adapter-preact-pure has fixed those issues for me. So with enzyme-adapter-preact-pure#^2.0.1 everything works like it should.

Categories