Search code examples
javascriptunit-testingiframetrello

How to write unit tests for for javascript 'plugin' (iframe) that expects certain global variables to be present


I am working on a Trello Power Up. The way they work is they load an iFrame you provide with some script tags that contain your custom code. You can see a working example here. The upshot is that when your code runs, there are certain "global" (not even sure if that's the right word) objects present that you interact with. For example:

const Promise = TrelloPowerUp.Promise;

TrelloPowerUp.initialize({
  'card-buttons': (t, options) => {
    return [{
      text: 'Awesome Button',
    }];
  }, 'show-settings': (t, options) =>{
    return t.popup({
      title: 'Settings',
      url: './settings.html',
      height: 184 // we can always resize later, but if we know the size in advance, its good to tell Trello
    });
  }
});

I am starting to add a little bit of complexity to this project and my habit is to use tdd/ write unit tests. I can't figure out how this code would be testable.

Is there some way to provide a mock 'TrelloPowerUp' global object before I run a mocha test? I tried:

TrelloPowerUp = {}
require('./client.js');

(The client.js script runs as soon as it is imported...) Unsurprisingly that didn't work.

I suppose I could import from another file that did have unit tests, to minimize the untestable code, something like:

import TrelloInitActions from './TrelloInitActions'

const Promise = TrelloPowerUp.Promise;

TrelloPowerUp.initialize({
  'card-buttons': TrelloInitActions.initButtons
}, 'show-settings': TrelloInitActions.showSettings
});

Thanks in advance for your help!


Solution

  • To solve this problem I am using react, if you find yourself in this situation check out https://www.npmjs.com/package/trello-react-scripts