Search code examples
javascripttestingmockingtypeerrorclipboard.js

TypeError: Clipboard.on is not a function


I am testing my clipboard tooltip code, but when I run the test it gives the error

TypeError: Clipboard.on is not a function

Test File

let clipboard_args;
class Clipboard {
    constructor(...args) {
        clipboard_args = args;
    }
}

mock_cjs("clipboard", Clipboard);

...
...
...

rm.update_elements($content);   // here the error is caused after calling this function

Main file

export const update_elements = ($content) => {

   ...
   ...
   ...

   clipboard.on('success', function(e) {                    //There error will not occur without this line
         show_copied_confirmation($copy_button[0]);
    });
};

The mocks seems support the bare minimum functionality needed to run the existing tests with the existing code. The code seems to be fine, but I am not sure what to do in order to fix the tests.


Solution

  • Adding the dummy on function does the trick.

    let clipboard_args;
    class Clipboard {
        constructor(...args) {
            clipboard_args = args;
        }
        on(success, show_copied_confirmation) {
           show_copied_confirmation();
        }
    }