【发布时间】:2016-07-19 16:19:03
【问题描述】:
我正在尝试为模拟真实用户输入的 ember 组件编写测试。例如:
<div>
<input class='js-input' type='text' value='{{ bar }}'> </input>
<button class='js-save' type='submit' {{action 'save'}}>
</div>
我的组件目前使用change 和keyUp 事件根据输入的内容计算另一个值,并即时验证输入:
import Ember from 'ember';
export default Ember.Component.extend({
bar: null,
modelBar: null,
updateBar: Ember.on('change', 'keyUp', function() {
let bar = this.get('bar');
if (bar.get('notValid')) {
bar = null;
this.set('bar', '');
}
this.set('modelBar', bar);
}),
actions: {
save() {
... save stuff ...
}
}
});
所以我一直在使用$('.js-input').val('some new value') 来模拟这个(推荐here,在“与渲染组件交互”下)。
test('Updates a thing', function(assert) {
assert.expect(1);
const newState = 'a new state';
this.set('actions.save', (newTaxes) => {
assert.ok(true, 'save has been called');
assert.equal(newState, this.get('modelBar'), 'model is updated correctly');
});
this.set('bar', 'initial state');
this.render(hbs`
{{my-component
baz=baz
}}
`);
this.$('.js-input').val(newState);
this.$('.js-input').trigger('change');
this.$('.js-save').click();
});
但是,当我运行测试时,change 事件没有使用this.get('bar') 获取输入的更新值(尽管如果我使用this.$('js-input').val() 可以看到它)。如果我添加观察者,我可以看到观察者获取属性的更新值,但仅在 触发自定义更改事件之后。
我尝试在 Ember 运行循环和 run.next 循环中包装东西,但这也没有帮助。有没有办法让这项工作,希望不需要依靠观察者? (该组件之前使用了观察者,但一些新的要求使事情变得更加复杂。)
【问题讨论】:
-
我可能会走得很远,但我相信
jQuery.sendKeys(请参阅此fiddle 中的示例)插件会做你想做的事情。 -
有趣!我将来可能会探索的东西:)