【问题标题】:How to determine if OnsenUI component is compiled in unit test单元测试中如何判断OnsenUI组件是否编译
【发布时间】:2019-12-22 22:05:42
【问题描述】:

我的项目是用vue-cordova-webpack template 构建的。我创建了一个 vue 组件。我的组件模板中有v-ons-input。我需要在组件的单​​元测试期间更改v-ons-input 的值。我只能在编译ons-input 之后才能做到这一点,因为只有在编译ons-input 之后才有input 内部(参见OnsenUI component compilation)。问题是编译是异步执行的,当 OnsenUI 组件准备好使用时,我没有找到任何“合法”的方法来捕获事件。

我该怎么办?我为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)
 })

是否有更“干净”的方法来确定 OnsenUI 组件已准备好在单元测试中使用(无需使用组件的内部方法进行操作)?

附:我知道不适用于测试环境的方法 - 为document(参见here)监听init 事件,但它在单元测试中不起作用。

【问题讨论】:

  • 根据the docs v-ons-input 应该与普通的input 标签几乎完全相同。在这种情况下,我认为你应该把它存起来,因为你应该测试 your 组件,而不是v-ons-input

标签: javascript unit-testing vue.js onsen-ui


【解决方案1】:

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

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

内部细节(可略过)

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

ons-input 注册期间,Onsen UI 使用函数contentReady 等待编译完成,但该函数不是公共 API 的一部分。但是,contentReady 使用 setTimeout(技术上是 setImmediate,但它相当于同一件事)as a fallback 因此,一旦你有效地做同样的事情,就使用 setTimeout

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

【讨论】:

  • 感谢您的回答。只是想补充一点,我将 setTimeout 包装在 promise function wait () { return new Promise(resolve => {setTimeout(resolve)})} 中,因为在 async 测试中使用它更方便。只需调用await wait(),然后找到ons-input 并进行断言。
猜你喜欢
  • 1970-01-01
  • 2012-01-15
  • 1970-01-01
  • 2023-03-03
  • 2011-01-01
  • 2017-02-08
  • 1970-01-01
  • 2017-04-29
相关资源
最近更新 更多