[Enterprise Search] Add Kea test helper for directly accessing listeners (#89061) (#89223)

* Add getListeners to Kea test helpers

* Update TelemetryLogic to use new getListeners helper

Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>

Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
This commit is contained in:
Constance 2021-01-25 14:22:37 -08:00 committed by GitHub
parent 7947aa257a
commit 57787c36d0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 30 additions and 11 deletions

View file

@ -120,4 +120,29 @@ export class LogicMounter {
public unmount = () => {
this.unmountFn();
};
/**
* Some tests (e.g. async tests, tests that expect thrown errors) need to access
* listener functions directly instead of calling `SomeLogic.actions.someListener`,
* due to how Kea invokes/wraps action fns by design.
*
* Example usage:
*
* const { mount, getListeners } = new LogicMounter(SomeLogic);
*
* it('some test', async () => {
* mount();
* const { someListener } = getListeners({ values: { someMockValue: false } });
*
* const mockBreakpoint = jest.fn();
* await someListener({ someMockArgument: true }, mockBreakpoint);
* });
*/
public getListeners = (listenersArgs: object = {}) => {
const { listeners } = this.logicFile.inputs[0];
return typeof listeners === 'function'
? (listeners as Function)(listenersArgs) // e.g., listeners({ values, actions, props }) => ({ ... })
: listeners; // handles simpler logic files that just define listeners: { ... }
};
}

View file

@ -4,20 +4,18 @@
* you may not use this file except in compliance with the Elastic License.
*/
import { resetContext } from 'kea';
import { JSON_HEADER as headers } from '../../../../common/constants';
import { mockHttpValues } from '../../__mocks__/http_logic.mock';
import { LogicMounter, mockHttpValues } from '../../__mocks__';
import { TelemetryLogic } from './';
import { TelemetryLogic } from './telemetry_logic';
describe('Telemetry logic', () => {
const { mount, getListeners } = new LogicMounter(TelemetryLogic);
const { http } = mockHttpValues;
beforeEach(() => {
jest.clearAllMocks();
resetContext({});
TelemetryLogic.mount();
mount();
});
describe('sendTelemetry', () => {
@ -36,11 +34,7 @@ describe('Telemetry logic', () => {
it('throws an error if the telemetry endpoint fails', async () => {
http.put.mockImplementationOnce(() => Promise.reject());
// To capture thrown errors, we have to call the listener fn directly
// instead of using `TelemetryLogic.actions.sendTelemetry` - this is
// due to how Kea invokes/wraps action fns by design.
const { sendTelemetry } = (TelemetryLogic.inputs[0] as any).listeners({ actions: {} });
const { sendTelemetry } = getListeners();
await expect(sendTelemetry({ action: '', metric: '', product: '' })).rejects.toThrow(
'Unable to send telemetry'