我正在尝试从此处遵循一个示例集成测试:https://guides.emberjs.com/release/release/testing/testing-components/(testing Action)
我的问题是,由于某种原因,测试输出会永久自动刷新?
测试代码:
test('Can handle submit action', async function (assert) {
/*
* THIS TEST HAS PROBLEMS
* THE PAGE CONSTANTLY REFRESHES FOR THIS TEST, NO IDEA WHY, NEED TO INVESTIGATE
*/
assert.expect(1);
// test double for the external action
this.set('externalAction', (actual) => {
const expected = {inputValue: 'test'};
assert.deepEqual(actual, expected, 'submitted value is passed to external action');
});
await render(hbs`{{user-form inputValue="test" saveAction=(action externalAction)}}`);
// click the button to submit the form
await click('#submitButton');
});
component.js:
import Component from '@ember/component';
import {computed} from '@ember/object';
export default Component.extend({
inputValue: '',
submitText: 'Save',
inputIsValid: computed('inputValue', function () {
return this.inputValue.length > 3;
}),
actions: {
save(inputValue) {
if (this.inputIsValid) {
this.saveAction(inputValue); // pass action handling to route that uses component
}
}
}
});
组件模板:
<br>
<br>
<form onsubmit={{action "save" inputValue}}>
{{#unless inputIsValid}}
<div style="color: red" class='validationMessage'>
Hey it is not valid!
</div>
{{/unless}}
<label id="inputLabel">{{inputLabel}}</label>
{{input type="text" id="input" placeholder=inputPlaceholder value=inputValue class="form-control"}}
<br>
<button type="submit" id="submitButton" class="btn btn-primary">{{submitText}}</button>
</form>
{{outlet}}
我认为这可能是因为模板中的表格不断提交,但事实并非如此,因为它只能单击一次提交。任何帮助非常感谢!
按照 @lux的建议写为注释;您需要进行以下操作以防止表单提交重新加载页面:
save(inputValue, event) {
event.preventDefault()
if (this.inputIsValid) {
this.saveAction(inputValue); // pass action handling to route that uses component
}
}
您收到event
作为最后一个参数,并调用preventDefault
告诉浏览器不要按照通常的方式处理事件。有关更好的解释,请参见MDN。