gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:26:59 27 4
gpt4 key购买 nike

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

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

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 组件已准备好在单元测试中使用(无需使用组件的内部方法进行操作)?

附:我知道不适合测试环境的方式 - 监听 init document 的事件(见 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应该保证内 input附于 setTimeout的回调运行。

关于javascript - 单元测试中如何判断OnsenUI组件是否编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57527046/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com