单元测试如何判断OnsenUI组件是否编译

How to determine if OnsenUI component is compiled in unit test

我的项目是用 vue-cordova-webpack template. I created a vue-component. There is v-ons-input inside the template of my component. I need to change the value of v-ons-input during the unit test of my component. I can do it only after ons-input is compiled, because only after compilation ons-input has input inside (see about OnsenUI component compilation) 构建的。问题是编译是异步执行的,当 OnsenUI 组件准备好使用时,我没有找到任何 "legit" 方法来捕获事件。

我该怎么办?我为 ons-input 的内部方法 _compile 创建了一个 sinon spy 并等待它被调用:

it('test', (done) => {
   const wrapper = mount(myVueComponent)

   // here I can't set a value for ons-input

   var spy = sinon.spy(wrapper.find('ons-input').element, '_compile')

   function waitForCall(spy) {
     return new Promise(function (resolve, reject) {
       (function wait() {
         if (spy.called) {
           return resolve()
         }
         setTimeout(wait, 10)
       })()
     })
   }

   waitForCall(spy).then(function () {
     // now ons-input is compiled and I can set a value for ons-input
     wrapper.find('ons-input').element.value = 'foo'
     ...
   }).then(done, done)
 })

是否有更多 "clean" 方法来确定 OnsenUI 组件是否已准备好用于单元测试(无需使用组件的内部方法进行操作)?

P.S。我知道不适用于测试环境的方式 - 监听 documentinit 事件(参见 here),但它在单元测试中不起作用。

setTimeout 应该和这里的任何东西一样好。

setTimeout(() => document.querySelector('ons-input input'));

内部细节(可跳过)

文件定义 VOnsInput imports ons-input,将 ons-input 注册为自定义元素。这是同步发生的,所以只要执行了 Vue 组件的脚本,就可以保证 ons-input 将被注册为自定义元素。

ons-input 的注册过程中,Onsen UI 使用函数 contentReady 等待编译完成,但该函数不属于 public API。然而,contentReady 使用 setTimeout(技术上 setImmediate 但它相当于同一件事)as a fallback 因此,一旦你有效地做同样的事情,就使用 setTimeout

简而言之,这意味着使用setTimeout应该保证当setTimeout的回调是运行时附加内部input