Skip to content
This repository has been archived by the owner on May 22, 2024. It is now read-only.

Commit

Permalink
[terra-functional-testing] Create a setLocale utility that updates te…
Browse files Browse the repository at this point in the history
…rra-application's locale (#524)

* [placeholder] initialize dispatchCustomEvent.

* [placeholder] attach to terra global. perhaps this is unnecessary.

* Revert "[placeholder] attach to terra global. perhaps this is unnecessary."

This reverts commit 093efe9.

* remove afterCommand short circuit

* add custom event dispatcher fixture

* update jest tests

* add wdio test

* reword unit tests

* add utility to terra global and update to object based api. add doc. export via
index file.

* remove console.log. revert back to single it block

* [placeholder] add setLocale utility; expose via terra global; update doc

* split customEventDispatcher into separate file. add unit test for setLocale

* update doc and error log

* correct typo in doc

* rename utility to setApplicationLocale. fix failing wdio test.

* rename setLocale fn to setApplicationLocale
  • Loading branch information
yuderekyu committed Jan 12, 2021
1 parent c7632df commit b873269
Show file tree
Hide file tree
Showing 10 changed files with 149 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* Utility to send a custom event containing metadata.
* @param {string} options.name - name of event
* @param {object} options.metaData - metadata pertaining to event
*/
const dispatchCustomEvent = (options) => {
const { name, metaData } = options;
try {
global.browser.execute((eventName, eventMetaData) => {
/* If IE support is removed, convert below to use event constructors. */
const event = document.createEvent('Event');
event.initEvent(eventName, true, true);
event.metaData = eventMetaData;
window.dispatchEvent(event);
}, name, metaData);
} catch (error) {
throw new Error(`dispatchCustomEvent failed: ${error}`);
}
};

module.exports = dispatchCustomEvent;
2 changes: 2 additions & 0 deletions packages/terra-functional-testing/src/commands/utils/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
const describeViewports = require('./describeViewports');
const getViewports = require('./getViewports');
const hideInputCaret = require('./hideInputCaret');
const setApplicationLocale = require('./setApplicationLocale');
const setViewport = require('./setViewport');

module.exports = {
describeViewports,
getViewports,
hideInputCaret,
setApplicationLocale,
setViewport,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const { Logger } = require('@cerner/terra-cli');
const dispatchCustomEvent = require('./dispatchCustomEvent');

const logger = new Logger({ prefix: '[terra-functional-testing:setApplicationLocale]' });

/**
* Updates terra-application's locale via custom event
* @param {string} locale - name of locale to update to
*/
const setApplicationLocale = (locale) => {
if (typeof locale === 'undefined' || !locale) {
logger.error(`Unsupported locale supplied to setApplicationLocale. "${locale}" is not a valid locale.`);
return;
}

const event = {
name: 'applicationBase.testOverride',
metaData: { locale },
};

dispatchCustomEvent(event);
};

module.exports = setApplicationLocale;
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const {
describeViewports,
getViewports,
hideInputCaret,
setApplicationLocale,
setViewport,
} = require('../commands/utils');

Expand Down Expand Up @@ -58,6 +59,7 @@ class TerraService {
global.expect.extend({ toBeAccessible });

// Setup and expose global utility functions.
global.Terra.setApplicationLocale = setApplicationLocale;
global.Terra.viewports = getViewports;
global.Terra.hideInputCaret = hideInputCaret;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ To get started ensure [docker](https://www.docker.com/) has been installed. The
Install with npm:

```
npm install --save-dev @cerner/terra-functional-testing
npm install --save-dev @cerner/terra-functional-testing
```

## Test Runner
Expand Down Expand Up @@ -81,7 +81,7 @@ The testing library integrates [axe-core](https://github.com/dequelabs/axe-core)

Axe will analyze the entire document when run and report accessibility violations. The following [tags](https://github.com/dequelabs/axe-core/blob/develop/doc/API.md#axe-core-tags) are enabled `wcag2a`, `wcag2aa`, `wcag21aa`, and `section508`. Each tag has an associated list of [rules](https://github.com/dequelabs/axe-core/blob/develop/doc/rule-descriptions.md) that will be checked against the document when axe is run.

Please note that not all accessibility testing can be automated. Axe provides a lightweight static analysis of the entire document to catch common accessibility violations, but it is the responsibility of each team and application to do thorough accessibility and functional testing manually when necessary.
Please note that not all accessibility testing can be automated. Axe provides a lightweight static analysis of the entire document to catch common accessibility violations, but it is the responsibility of each team and application to do thorough accessibility and functional testing manually when necessary.

### Terra.validates.accessibility

Expand Down Expand Up @@ -116,7 +116,7 @@ A screenshot can be captured at any given point in a test. The captured screensh

The element assertion should only be invoked inside an `it` block. Invoking the assertion will capture a screenshot at the time it is invoked. If no reference screenshot exists, one will be created in the `reference` folder with the given screenshot name. If such reference screenshot already exists, the new screenshot will be compared with the reference screenshot to validate visually that they are within the mismatch tolerance. If the mismatch exceeds the tolerance, the test step will fail and a screenshot showing the difference will be generated.

A name must be provided to be used as the screenshot name. In addition to capturing a screenshot and performing screenshot validation, the assertion also runs accessibility checks on the entire document.
A name must be provided to be used as the screenshot name. In addition to capturing a screenshot and performing screenshot validation, the assertion also runs accessibility checks on the entire document.

```js
it('should validate the element', () => {
Expand Down Expand Up @@ -159,3 +159,14 @@ it('should hide the caret', () => {
expect(element.getCssProperty('caretColor').value).to.equal('rgba(0,0,0,0)');
});
```

## Locale Update (Case by Case)

### Terra.setApplicationLocale
Use `Terra.setApplicationLocale` to update a terra application's locale on a case by case basis; particularly useful for testing locale changes on a deployed application. This method accepts a string containing the `locale` to update to.

```js
it('should update an application's locale, () => {
Terra.setApplicationLocale('en');
});
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="<%= htmlWebpackPlugin.options.lang %>" dir="ltr">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dispatch Custom Event</title>
</head>
<body style="height: 100%;">
<div>
Test Custom Event Dispatcher
<p id="custom-event-paragraph"></p>
</div>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const dispatchCustomEvent = require('../../../../src/commands/utils/dispatchCustomEvent');

describe('dispatchCustomEvent', () => {
it('executes a specified function via browser.execute', () => {
const mockFn = jest.fn();
global.browser = {
execute: mockFn,
};

dispatchCustomEvent({ name: 'mock' });
expect(mockFn).toBeCalled();
});

it('throws an error outputted by browser.execute', () => {
const mockError = new Error('mock error');
global.browser = {
execute: () => { throw mockError; },
};

expect(() => dispatchCustomEvent({ name: 'mock' })).toThrow(`dispatchCustomEvent failed: ${mockError}`);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const setApplicationLocale = require('../../../../src/commands/utils/setApplicationLocale');
const dispatchCustomEvent = require('../../../../src/commands/utils/dispatchCustomEvent');

jest.mock('../../../../src/commands/utils/dispatchCustomEvent');

describe('setApplicationLocale', () => {
it('executes dispatchCustomEvent with a specified locale', () => {
setApplicationLocale('ar');
const expectedEvent = {
name: 'applicationBase.testOverride',
metaData: { locale: 'ar' },
};
expect(dispatchCustomEvent).toHaveBeenCalledWith(expectedEvent);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/* global $ */
const dispatchCustomEvent = require('../../src/commands/utils/dispatchCustomEvent');

describe('dispatchCustomEvent', () => {
it('sends a custom event that injects a string into a paragraph', () => {
browser.url('/dispatch-custom-event.html');

/* Setup event listener that injects a string into a paragraph. */
browser.execute(() => {
const eventListenerHandler = (event) => {
const paragraph = document.getElementById('custom-event-paragraph');
const { metaData } = event;
const { injectedString } = metaData;
paragraph.textContent = injectedString;
};

window.addEventListener('mockCustomEvent', eventListenerHandler);
});

const injectedString = 'mock';
dispatchCustomEvent({
name: 'mockCustomEvent',
metaData: { injectedString },
});
const actualString = $('#custom-event-paragraph').getText();
expect(actualString).toEqual(injectedString);
});
});
6 changes: 6 additions & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ module.exports = (env = {}) => {
chunks: ['index'],
filename: 'insufficient-color-contrast.html',
}),
new HtmlWebpackPlugin({
lang: defaultLocale,
template: path.join(__dirname, 'packages', 'terra-functional-testing', 'tests', 'fixtures', 'dispatch-custom-event.html'),
chunks: ['index'],
filename: 'dispatch-custom-event.html',
}),
],
output: {
path: path.join(process.cwd(), 'build'),
Expand Down

0 comments on commit b873269

Please sign in to comment.