| 1 | /** @odoo-module alias=@web/../tests/legacy_tests/helpers/test_utils_fields default=false */ |
| 2 | |
| 3 | /** |
| 4 | * Field Test Utils |
| 5 | * |
| 6 | * This module defines various utility functions to help testing field widgets. |
| 7 | * |
| 8 | * Note that all methods defined in this module are exported in the main |
| 9 | * testUtils file. |
| 10 | */ |
| 11 | |
| 12 | import testUtilsDom from "./test_utils_dom"; |
| 13 | |
| 14 | //------------------------------------------------------------------------- |
| 15 | // Public functions |
| 16 | //------------------------------------------------------------------------- |
| 17 | |
| 18 | /** |
| 19 | * Sets the value of an element and then, trigger all specified events. |
| 20 | * Note that this helper also checks the unicity of the target. |
| 21 | * |
| 22 | * Example: |
| 23 | * testUtils.fields.editAndTrigger($('selector'), 'test', ['input', 'change']); |
| 24 | * |
| 25 | * @param {jQuery|EventTarget} el should target an input, textarea or select |
| 26 | * @param {string|number} value |
| 27 | * @param {string[]} events |
| 28 | * @returns {Promise} |
| 29 | */ |
| 30 | export async function editAndTrigger(el, value, events) { |
| 31 | if (el instanceof jQuery) { |
| 32 | if (el.length !== 1) { |
| 33 | throw new Error(`target ${el.selector} has length ${el.length} instead of 1`); |
| 34 | } |
| 35 | el.val(value); |
| 36 | } else { |
| 37 | el.value = value; |
| 38 | } |
| 39 | return testUtilsDom.triggerEvents(el, events); |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Sets the value of an input. |
| 44 | * |
| 45 | * Note that this helper also checks the unicity of the target. |
| 46 | * |
| 47 | * Example: |
| 48 | * testUtils.fields.editInput($('selector'), 'somevalue'); |
| 49 | * |
| 50 | * @param {jQuery|EventTarget} el should target an input, textarea or select |
| 51 | * @param {string|number} value |
| 52 | * @returns {Promise} |
| 53 | */ |
| 54 | export async function editInput(el, value) { |
| 55 | return editAndTrigger(el, value, ['input']); |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * Helper to trigger a key event on an element. |
| 60 | * |
| 61 | * @param {string} type type of key event ('press', 'up' or 'down') |
| 62 | * @param {jQuery} $el |
| 63 | * @param {string} key |
| 64 | * @returns {Promise} |
| 65 | */ |
| 66 | function triggerKey(type, $el, key) { |
| 67 | type = 'key' + type; |
| 68 | const params = {}; |
| 69 | params.key = key; |
| 70 | return testUtilsDom.triggerEvent($el, type, params); |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * Helper to trigger a keydown event on an element. |
| 75 | * |
| 76 | * @param {jQuery} $el |
| 77 | * @param {number|string} key @see triggerKey |
| 78 | * @returns {Promise} |
| 79 | */ |
| 80 | function triggerKeydown($el, key) { |
| 81 | return triggerKey('down', $el, key); |
| 82 | } |
| 83 | |
| 84 | export default { |
| 85 | editAndTrigger, |
| 86 | editInput, |
| 87 | triggerKeydown, |
| 88 | }; |