Skip to content

Commit

Permalink
feat: add @ima/testing-library
Browse files Browse the repository at this point in the history
  • Loading branch information
Filipoliko committed Aug 15, 2024
1 parent fbbd942 commit d0ec9c1
Show file tree
Hide file tree
Showing 22 changed files with 800 additions and 97 deletions.
247 changes: 152 additions & 95 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"./packages/devtools",
"./packages/error-overlay",
"./packages/react-page-renderer",
"./packages/testing-library",
"./packages/storybook-integration",
"./website"
],
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/boot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export interface Resources {
*/
export interface Environment {
[key: string]: unknown;
$Debug: GlobalImaObject['$Version'];
$Debug: GlobalImaObject['$Debug'];
$Language: Record<string, string>;
$Version: GlobalImaObject['$Version'];
$App: GlobalImaObject['$App'];
Expand Down
2 changes: 1 addition & 1 deletion packages/react-page-renderer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
},
"devDependencies": {
"@cfaester/enzyme-adapter-react-18": "^0.7.0",
"@testing-library/react": "^14.0.0",
"@testing-library/react": "^16.0.0",
"@types/react": "^18.0.33",
"@types/react-dom": "^18.0.6",
"@types/webpack-env": "^1.16.3",
Expand Down
2 changes: 2 additions & 0 deletions packages/server/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ declare module '@ima/server' {
}

export function createIMAServer(params: {
applicationFolder?: string;
processEnvironment?: (environment: Environment) => Environment;
environment?: Environment;
logger?: any;
emitter?: Emitter;
Expand Down
4 changes: 4 additions & 0 deletions packages/testing-library/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
*
!dist/**/*
!package.json
!jest-preset.js
21 changes: 21 additions & 0 deletions packages/testing-library/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2022 Seznam.cz a.s.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
106 changes: 106 additions & 0 deletions packages/testing-library/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<p align="center">
<img height="130" src="https://imajs.io/img/logo.svg">
</p>

<h1 align="center">@ima/testing-library</h1>
<p align="center"><i>Testing library for IMA.js applications.</i>
</p>

---

## IMA Testing Library

The `@ima/testing-library` contains utilities for testing IMA.js applications. It provides integration with [Jest](https://jestjs.io), [React Testing Library](https://testing-library.com/docs/react-testing-library/intro) (RTL for short) amd [Testing Library Jest DOM](https://testing-library.com/docs/ecosystem-jest-dom).

## Installation

Install the new dependencies. Note that RTL dependencies are only peer dependencies and you should specify them in your project.

```bash
npm install -D @ima/testing-library @testing-library/dom @testing-library/jest-dom @testing-library/react
```

Configure jest preset in your jest config file.

```json
{
"preset": "@ima/testing-library"
}
```

Everything should start working out of the box for a typical IMA.js application. If you are trying to setup this library in a monorepo or an npm package, you might have to do some tweaks with the configuration. In this case, you need the jest config file to be in non-json format.

```javascript
const { setImaTestingLibraryConfig, FALLBACK_APP_MAIN_PATH } = require('@ima/testing-library');

setImaTestingLibraryConfig({
// your custom config
appMainPath: FALLBACK_APP_MAIN_PATH, // There is a default app main file as part of the package, it contains only the minimal setup and it might be enough for you if you don't have any real app main file.
imaConfigPath: 'path/to/your/ima.config.js',
applicationFolder: '/path/to/folder/containing/server/folder',
});

module.exports = {
preset: '@ima/testing-library'
};
```

## Usage

IMA Testing Library is re-exporting everything from `@testing-library/react`. It provides the default context wrapper for the `render` method. Thanks to this, the default example from the React Testing Library documentation will work out of the box. You just need to import the `render` method from the `@ima/testing-library` package.

```javascript
import { render } from '@ima/testing-library';

test('renders learn react link', () => {
const { getByText } = render(<App />);
const linkElement = getByText(/learn react/i);

expect(linkElement).toBeInTheDocument();
});
```

You might need to specify custom additions to the context, or mock some parts of the IMA application. You can do this by providing a custom context wrapper and using the `@ima/testing-library` specific utilities.

```javascript
import { render, getContextWrapper, getContextValue, initImaApp } from '@ima/testing-library';

test('renders learn react link with custom context wrapper', () => {
const ContextWrapper = getContextWrapper();
const { getByText } = render(<App />, {
wrapper: <MyCustomWrapper><CotextWrapper /></MyCustomWrapper>,
});
const linkElement = getByText(/learn react/i);

expect(linkElement).toBeInTheDocument();
});

test('renders learn react link with custom context value', () => {
const contextValue = getContextValue();

contextValue.$Utils.$Foo = jest.fn(() => 'bar');

const ContextWrapper = getContextWrapper(contextValue);
const { getByText } = render(<App />, {
wrapper: ContextWrapper,
});
const linkElement = getByText(/learn react/i);

expect(linkElement).toBeInTheDocument();
});

test('renders learn react link with custom app configuration', () => {
const app = initImaApp();

app.oc.get('$Utils').$Foo = jest.fn(() => 'bar');

const contextValue = getContextValue(app);
const ContextWrapper = getContextWrapper(contextValue);
const { getByText } = render(<App />, {
wrapper: ContextWrapper,
});
const linkElement = getByText(/learn react/i);

expect(linkElement).toBeInTheDocument();
});
```
6 changes: 6 additions & 0 deletions packages/testing-library/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const defaultConfig = require('../../jest.config.base.js');

module.exports = {
...defaultConfig,
testRegex: '(/__tests__/).*Spec\\.[jt]s$',
};
48 changes: 48 additions & 0 deletions packages/testing-library/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"name": "@ima/testing-library",
"version": "19.6.0",
"description": "Testing library for IMA.js applications.",
"keywords": [
"IMA.js",
"react",
"testing",
"library"
],
"bugs": {
"url": "https://github.com/seznam/ima/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/seznam/ima.git",
"directory": "packages/testing-library"
},
"license": "MIT",
"author": "Filip Satek <[email protected]>",
"scripts": {
"dev": "node ../plugin-cli/dist/bin/ima-plugin.js dev",
"build": "node ../plugin-cli/dist/bin/ima-plugin.js build",
"link": "node ../plugin-cli/dist/bin/ima-plugin.js link",
"lint": "eslint './**/*.{js,jsx,ts,tsx}'",
"test": "jest -c jest.config.js"
},
"exports": {
".": {
"types": "./dist/esm/index.d.ts",
"import": "./dist/esm/index.js",
"default": "./dist/cjs/index.js"
},
"./jest-preset": "./dist/cjs/jest-preset.js",
"./jestSetupFileAfterEnv": "./dist/cjs/jestSetupFileAfterEnv.js"
},
"peerDependencies": {
"@ima/core": ">=19.0.0",
"@ima/react-page-renderer": ">=19.0.0",
"@testing-library/dom": ">=10.0.0",
"@testing-library/jest-dom": ">=6.0.0",
"@testing-library/react": ">=16.0.0"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
}
}
Empty file.
53 changes: 53 additions & 0 deletions packages/testing-library/src/app/config/bind.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {
ComponentUtils,
InitBindFunction,
PageRenderer,
Window,
} from '@ima/core';
import {
defaultCssClasses as cssClassNameProcessor,
PageRendererFactory,
ServerPageRenderer,
} from '@ima/react-page-renderer';
import { ClientPageRenderer } from '@ima/react-page-renderer/renderer/ClientPageRenderer';

declare module '@ima/core' {
interface OCAliasMap {
$CssClasses: () => typeof cssClassNameProcessor;
$PageRendererFactory: PageRendererFactory;
}
}

export const initBindApp: InitBindFunction = (ns, oc) => {
// UI components
oc.bind('$CssClasses', function () {
return cssClassNameProcessor;
});

// You can set own Component utils here
oc.get(ComponentUtils).register({
$CssClasses: '$CssClasses',
});

oc.inject(PageRendererFactory, [ComponentUtils]);
oc.bind('$PageRendererFactory', PageRendererFactory);

if (oc.get(Window).isClient()) {
oc.provide(PageRenderer, ClientPageRenderer, [
PageRendererFactory,
'$Helper',
'$Dispatcher',
'$Settings',
Window,
]);
} else {
oc.provide(PageRenderer, ServerPageRenderer, [
PageRendererFactory,
'$Helper',
'$Dispatcher',
'$Settings',
]);
}

oc.bind('$PageRenderer', PageRenderer);
};
45 changes: 45 additions & 0 deletions packages/testing-library/src/app/config/settings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { InitSettingsFunction } from '@ima/core';

export const initSettings: InitSettingsFunction = (ns, oc, config) => {
return {
prod: {
$Version: config.$Version,
$Http: {
defaultRequestOptions: {
timeout: 7000, // Request timeout
repeatRequest: 0, // Count of automatic repeated request after failing request.
ttl: 60000, // Default time to live for cached request in ms.
fetchOptions: {
mode: 'cors',
headers: {
// Set default request headers
Accept: 'application/json',
'Accept-Language': config.$Language,
},
},
cache: false, // if value exists in cache then returned it else make request to remote server.
},
cacheOptions: {
prefix: 'http.', // Cache key prefix for response bodies (already parsed as JSON) of completed HTTP requests.
},
},
$Router: {
/**
* Middleware execution timeout, see https://imajs.io/basic-features/routing/middlewares#execution-timeout
* for more information.
*/
middlewareTimeout: 30000,
},
$Cache: {
enabled: false, //Turn on/off cache for all application.
ttl: 60000, // Default time to live for cached value in ms.
},
$Page: {
$Render: {
documentView: () => {}, // eslint-disable-line @typescript-eslint/no-empty-function
masterElementId: 'page',
},
},
},
};
};
15 changes: 15 additions & 0 deletions packages/testing-library/src/app/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as ima from '@ima/core';

import { initBindApp } from './config/bind';
import { initSettings } from './config/settings';

const getInitialAppConfigFunctions = () => {
return {
initBindApp,
initRoutes: () => {}, // eslint-disable-line @typescript-eslint/no-empty-function
initServicesApp: () => {}, // eslint-disable-line @typescript-eslint/no-empty-function
initSettings,
};
};

export { getInitialAppConfigFunctions, ima };
57 changes: 57 additions & 0 deletions packages/testing-library/src/configuration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import type { Environment } from '@ima/core';

export interface Configuration {
/**
* The path to the main application file. This file should be exporting getInitialAppConfigFunctions and ima keys.
*/
appMainPath: string;
/**
* The path to the IMA configuration file. This can be only configured once before first `initImaApp` call and cannot be reconfigured later.
*/
imaConfigPath: string;
/**
* The protocol of the application. This can be only configured in the jest config file and cannot be reconfigured later.
*/
protocol: string;
/**
* The host of the application. This can be only configured in the jest config file and cannot be reconfigured later.
*/
host: string;
/**
* The locale of the application. This will affect the language of the application.
*/
locale: string;
/**
* The process environment configuration. This allows you to change the environment configuration that will be available in jsdom.
* This can be only configured in the jest config file and cannot be reconfigured later.
*/
processEnvironment: (env: Environment) => Environment;
/**
* The path to the application folder. This can be only configured in the jest config file and cannot be reconfigured later.
*/
applicationFolder: string | undefined;
}

const configuration: Configuration = {
appMainPath: 'app/main.js',
imaConfigPath: 'ima.config.js',
protocol: 'https:',
host: 'imajs.io',
locale: 'en',
processEnvironment: env => env,
applicationFolder: undefined,
};

/**
* Get the current configuration.
*/
export function getImaTestingLibraryConfig() {
return configuration;
}

/**
* Modify the current configuration.
*/
export function setImaTestingLibraryConfig(config: Partial<Configuration>) {
Object.assign(configuration, config);
}
Loading

0 comments on commit d0ec9c1

Please sign in to comment.