When I'm trying to run tests with using @open-wc/testing library I'm getting an error like below:
WebComponent which I try to test is written in Lit and connect to redux-toolkit:
import { LitElement, html } from 'lit';
import store from './redux/store/store';
import { connect } from 'pwa-helpers';
export class TestComponent extends connect(store)(LitElement) {
render() {
return html`<div>test</div>
`;
}
}
customElements.define('test-component', TestComponent);
My store file:
import { Action, AnyAction, ThunkAction, ThunkDispatch, configureStore } from '@reduxjs/toolkit';
import { IndicatorSlice } from './features/indicatorSlice.js';
const store = configureStore({
reducer: {
indicator: IndicatorSlice.reducer,
},
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export type AppThunk<ReturnType = void> = ThunkAction<
ReturnType,
RootState,
unknown,
Action<string>
>;
export const dispatch: ThunkDispatch<RootState, void, AnyAction> = store.dispatch;
export default store;
My unit test:
import { html } from 'lit';
import { fixture, expect } from '@open-wc/testing';
import type { TestComponent } from '../src/test-component.js';
import '../src/test-component.js';
describe('TestComponent', () => {
let element: TestComponent;
beforeEach(async () => {
element = await fixture(html`<test-component></test-component>`);
});
it('renders a div', () => {
const div = element.shadowRoot!.querySelector('div')!;
expect(div).to.exist;
expect(div.textContent).to.equal('test');
});
});
Does anyone have an idea what could be causing this error? Where to look for the problem?
The ESM build of @reduxjs/toolkit
package appears to contain references to process.env.NODE_ENV
which isn't available in the browser which is why you're getting ReferenceError: process is not defined
.
You could try replacing those out with a plugin in your web test runner config.
// web-test-runner.config.js
import rollupReplace from '@rollup/plugin-replace';
import { fromRollup } from '@web/dev-server-rollup';
const replace = fromRollup(rollupReplace);
export default {
// ...
plugins: [
replace({
'process.env.NODE_ENV': JSON.stringify('development'),
}),
],
}
See https://modern-web.dev/docs/dev-server/plugins/rollup/ and https://www.npmjs.com/package/@rollup/plugin-replace