How to combine configuration of enzyme and react-testing-library in setup.test.js - react-testing-library

Our project has both enzyme and testing-library.
My goal is to overwrite getByTestId to my custom.
But when I'm adding the second configuration to my setup.test.js - some tests become failing with Found multiple elements with the text.
setup.test.js:
const { configure } = require("enzyme");
const Adapter = require("enzyme-adapter-react-16");
import { configure as conf } from "#testing-library/react";
window.__config = {};
conf({ testIdAttribute: "data-my-test-id" });
configure({ adapter: new Adapter() });
My versions:
"enzyme": "^3.11.0",
"#testing-library/react": "^11.0.4",

This is happening because expected cleanup doesn't work.
Move below configuration to a new file, let's say "env-setup.js"
import { configure as conf } from "#testing-library/react";
conf({ testIdAttribute: "data-my-test-id" });
Now, in jest.config.js:
{
setupFilesAfterEnv: ['<existing_setup_file_path>', '<path>/env-setup.js']
}

Related

SvelteKit console error "window is not defined" when i import library

I would like to import apexChart library which using "window" property, and i get error in console.
[vite] Error when evaluating SSR module /src/routes/prehled.svelte:
ReferenceError: window is not defined
I tried use a apexCharts after mount, but the error did not disappear.
<script>
import ApexCharts from 'apexcharts'
import { onMount } from 'svelte'
const myOptions = {...myOptions}
onMount(() => {
const chart = new ApexCharts(document.querySelector('[data-chart="profit"]'), myOptions)
chart.render()
})
</script>
I tried import a apexCharts when i am sure that browser exist.
import { browser } from '$app/env'
if (browser) {
import ApexCharts from 'apexcharts'
}
But i got error "'import' and 'export' may only appear at the top level"
I tried disable ssr in svelte.config.js
import adapter from '#sveltejs/adapter-static';
const config = {
kit: {
adapter: adapter(),
prerender: {
enabled: false
},
ssr: false,
}
I tried to create a component in which I import apexChart library and I created a condition that uses this component only if a browser exists
{ #if browser }
<ProfitChart />
{ /if }
Nothing helped.
Does anyone know how to help me please?
The easiest way is to simply include apexcharts like a standalone library in your webpage like this:
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
And then simply use it in the onMount:
onMount(() => {
const chart = new ApexCharts(container, options)
chart.render()
})
You can add this line either in your app.html or include it where it's required with a <svelte:head> block.
An alternative way would be to dynamically import during onMount:
onMount(async () => {
const ApexCharts = (await import('apexcharts')).default
const chart = new ApexCharts(container, options)
chart.render()
})
As an extra: use bind:this instead of document.querySelector to get DOM elements, that would be the more 'svelte' way.
I have found the last option with the Vite plugin to work best with less code in the end but will lose intellisense in vscode and see import highlighted as error (temp workaround at end): https://kit.svelte.dev/faq#how-do-i-use-x-with-sveltekit-how-do-i-use-a-client-side-only-library-that-depends-on-document-or-window
Install vite plugin: npm i -D vite-plugin-iso-import
Add plugin to svelte.config.js:
kit: {
vite: {
plugins: [
isoImport(),
],
Add plugin to TypeScript config (if you use TS):
"compilerOptions": {
"plugins": [{ "name": "vite-plugin-iso-import" }],
Use as normal but note the "?client" on the import:
<script context="module">
import { chart } from 'svelte-apexcharts?client';
import { onMount } from 'svelte'
let myOptions = {...myOptions}
onMount(() => {
myOptions = {...updated options/data}
});
</script>
<div use:chart={myOptions} />
Debugging note:
To have import not highlighting as an error temporarily, just:
npm run dev, your project will compile fine, then test in browser to execute at least once.
remove ?client now, save and continue debugging as usual.
For all of you trying to import dynamically into a js or ts file, try the following:
Import your package during on mount in any svelte component.
onMount(async () => {
const Example = await import('#creator/examplePackage');
usePackageInJSOrTS(Example.default);
});
Use the imported package in your js/ts function. You need to pass the default value of the constructor.
export function usePackageInJsOrTs(NeededPackage) {
let neededPacakge = new NeededPackage();
}

Nuxt vuex - moving store from Vue

I have been fiddling with moving a tutorial I did in Vue to Nuxt. I have been able to get everything working, however I feel I'm not doing it the "proper way". I have added the Nuxt axios module, but wasnt able to get it working, so I ended up just using the usual axios npm module. Here is my store:
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(Vuex)
Vue.use(VueAxios, axios)
export const state = () => ({
events: []
})
export const mutations = {
setEvents: (state, events) => {
state.events = events
}
}
export const actions = {
loadEvents: async context => {
let uri = 'http://localhost:4000/events';
const response = await axios.get(uri)
context.commit('setEvents', response.data)
}
}
I would like to know how to re-write this store using the #nuxtjs/axios module. I also didnt think I'd need to import vuex here, but if I dont, my app doesn't work.
Thanks for any help!
Using the #nuxtjs/axios module, you can configure axios inside your nuxt.config.js:
// nuxt.config.js
export default {
modules: [
'#nuxtjs/axios',
],
axios: {
// proxy: true
}
}
You can use it inside your store (or components) with this.$axios
// In store
{
actions: {
async getIP ({ commit }) {
const ip = await this.$axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
}
}

Can't set React-Leaftlet Maps CRS using a JSON variable

I can't set the crs for React-Leaflet using this code:
import CONFIG from 'config/config.json';
.
.
.
.
<Map
ref={(m) => { this.leafletMap = m; }}
center={this.props.mapCenter}
zoom={zoomLevel}
crs={CRS.EPSG900913} // This works
crs={CONFIG.leafletMapCRS} // This doesn't
>
Here's my config.json file
{
"leafletMapURL": "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
"leafletMapCRS": "CRS.EPSG900913"
}
The leafletMapURL config entry works fine but the leafletMapCRS doesn't work for some reason. Any help is appreciated.
CRS is an object with some properties. In your config.json you are making it a string. So what you need to do to make this work is to remove "" and then import CRS from 'leaflet'. After you do that you will see that you have to make your file a .js instead of .json to be able to import CRS.
therefore you would have:
import { CRS } from "leaflet";
export const config = () => {
return {
leafletMapURL: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
leafletMapCRS: CRS.EPSG900913
};
};
and then:
import { config } from "./config";
...
function App() {
const bounds = [[-26.5, -25], [1021.5, 1023]];
const configs = config();
return (
<Map
center={[0, 0]}
zoom={0}
style={{ height: "100vh" }}
crs={configs.leafletMapCRS} // This works
>
<ImageOverlay
url="https://leafletjs.com/examples/crs-simple/uqm_map_full.png"
bounds={bounds}
/>
</Map>
);
}
Last but not least are you sure you can use CRS.EPSG900913? as the available reference systems are described here and CRS.EPSG900913 is not included there.
Demo

How can we use the On Prepare function in config File while i am trying to run multiple Spec files

In the Config File i am using the On Prepare Function for the purpose of assigning the property data test id as value
But for the first spec file execution the on prepare is picked up
but on the next execution of the Spec , the on prepare function is not getting picked up
import { Config } from "protractor/built/config";
import { by } from "protractor";
// import { encode } from "punycode";
function encode(file) {
var stream = require('fs').readFileSync(file);
return new Buffer(stream).toString('base64');
}
export let config: Config = {
// The address of a running selenium server.
//seleniumAddress: 'http://localhost:4444/wd/hub',
directConnect:true,
allScriptsTimeout:1500000,
// Capabilities to be passed to the webdriver instance.
capabilities: {
browserName: 'chrome',
'chromeOptions': {
'extensions': [encode('C:/Users/koanand/Documents/Protractor/ASR/2.2.9_0.crx')]
}
},
onPrepare: function () {
by.addLocator('testId', function(value, parentElement) {
parentElement = parentElement || document;
var nodes = parentElement.querySelectorAll('[data-test-id]');
return Array.prototype.filter.call(nodes, function(node) {
return (node.getAttribute('data-test-id') === value);
});
});
},
// Spec patterns are relative to the configuration file location passed
// to protractor (in this example conf.js).
// They may include glob patterns.
specs: ['C:/Users/anand/Documents/Protractor/ASR/TS-Output/specs/directasr.js',
'C:/Users/anand/Documents/Protractor/ASR/TS-Output/specs/products.js'
],
// Options to be passed to Jasmine-node.
jasmineNodeOpts: {
showColors: true, // Use colors in the command line report.
defaultTimeoutInterval : 150000
}
};
i am observing the below error
Message:
Failed: protractor_1.by.testID is not a function
Stack:
TypeError: protractor_1.by.testID is not a function
at new productlist (C:\Users\koanand\Documents\Protractor\ASR\pageobject\productlist.ts:19:45)
at product.selectingproductlist (C:\Users\koanand\Documents\Protractor\ASR\specs\classproductlist.ts:14:32)
at UserContext.<anonymous> (C:\Users\koanand\Documents\Protractor\ASR\specs\products.ts:21:21)
at C:\Users\koanand\Documents\Protractor\ASR\node_modules\jasminewd2\index.js:108:15
at new ManagedPromise (C:\Users\koanand\Documents\Protractor\ASR\node_modules\selenium-webdriver\lib\promise.js:1077:7)
at ControlFlow.promise (C:\Users\koanand\Documents\Protractor\ASR\node_modules\selenium-webdriver\lib\promise.js:2505:12)
at schedulerExecute (C:\Users\koanan
d\Docume
Use BeforeAll() in each spec file & write whatever you want to execute before each spec starts
May following link help you to clear your doubts for onPrepare and what to use in pace of it.
OnPrepare function in Protractor

aurelia/skeleton-plugin cant run test on custum element

i have created an aurelia plugin using the skelton-plugin https://github.com/aurelia/skeleton-plugin i am now looking at writing unit tests for it.
i am stuggling to get a unit test running for a custom element ive added to the project. i started with the 'testing a custom element' example from http://aurelia.io/hub.html#/doc/article/aurelia/testing/latest/testing-components/3
template:
<template>
<div class="firstName">${firstName}</div>
</template>
vm
import {bindable} from 'aurelia-framework';
export class MyComponent {
#bindable firstName;
}
i added this to the src folder.
my test code is
import {StageComponent} from 'aurelia-testing';
import {bootstrap} from 'aurelia-bootstrapper';
describe('MyComponent', () => {
let component;
beforeEach(() => {
component = StageComponent
.withResources('my-component')
.inView('<my-component first-name.bind="firstName"></my-component>')
.boundTo({ firstName: 'Bob' });
});
it('should render first name', done => {
component.create(bootstrap).then(() => {
const nameElement = document.querySelector('.firstName');
expect(nameElement.innerHTML).toBe('Bob');
done();
}).catch(e => { console.log(e.toString()) });
});
afterEach(() => {
component.dispose();
});
});
i jspm installed aurelia-bootstrapper and aurelia-testing to get it running.
im now getting the error
Error{stack: '(SystemJS) XHR error (404 Not Found) loading http://localhost:9876/base/my-component.js
so it looks like karma cant find my component. i checked the karma.config file and the jspm loadFiles: ['test/setup.js', 'test/unit/**/*.js'], looks correct.
has any one run into a similar issue?
solved the issue.
in karma.config.js file needed to change
serveFiles: ['src//.']
to
serveFiles: ['src//*.js', 'src/**/*.html']