我正在编写一个验收测试,其中用户填写表单并向第三方资源发出ajax请求。我正在嘲笑Ember CLI Mirage的请求。ember.js:使用ajax请求进行验收测试
我正在写一个基本的工作示例,我会在我的测试通过后重构。我知道我需要将我的请求抽象为一个服务或实用程序,但是我不喜欢重构我的代码,而无需对其进行工作测试。
我的代码似乎工作,但是,当我返回一个结果,改变模板中的某些内容,我无法通过测试。
重要的是要注意:我嘲笑的第三方API是不安宁的。
这里是海市蜃楼配置:
export default function() {
this.post('/LogonAction',() => {
return {foo: 'bar'};
});
}
我还没有设置Web服务的规范网址呢。它应该是一个外部服务。
而且我的组件:
import Ember from 'ember';
export default Ember.Component.extend({
result: null,
errors: null,
usernameTextChanged: function() { this.reset(); }.observes('username'),
passwordTextChanged: function() { this.reset(); }.observes('password'),
reset() {
this.set('errors', null);
this.set('result', null);
},
actions: {
sync() {
this.reset();
// TODO abstract out validation and add more use cases
if(this.get('username') === undefined || this.get('password') === undefined) {
this.set('errors', 'Please fill out the form');
}
else {
let params = { userId: this.get('username'), passwd: this.get('password') }
this.set('test', 'foos'); //just checking...
// TODO abstract out into a utility and move config values into config
Ember.$.post('/LogonAction', params).then((r) => {
// When I run tests, this renders to console.
console.log('promise happened 1', r, this.get('result'));
// Fails here. I don't know why.
this.set('result', true);
// This does not execute
console.log('promise happened 2', this.get('result'));
});
}
}
}
});
你会看到,我输出到控制台两次,这样我就可以对其进行调试。我不确定这是在编写测试时调试的正确方法。
这是我的模板:
<form id="logon" {{action 'sync' on='submit'}}>
{{input value=username type="text" class="username" placeholder="Your username"}}
{{input value=password type="password" class="password"}}
<button>Click me</button>
[[{{test}}]] <!-- this is just debugging -->
{{#if result}}
<div id="result">Sync complete</div>
{{/if}}
{{#if errors}}
<div id="result">{{errors}}</div>
{{/if}}
</form>
最后,我的测试:
test('logging in', assert => {
server.createList('LogonAction', 0);
visit('/');
console.log(0);
fillIn('input.username', 'foo');
fillIn('input.password', 'bar');
click('button');
console.log(1);
andThen(() => {
// The above console logs have happened.
// It does not have the div#result tag in it!
console.log(find('#logon').html());
assert.equal(find('#result').text(), 'Sync complete'); // fails.
});
});
控制台登录(我认为)告诉我,我才断言,页面显示的承诺得到解决结果给用户。但我无法让这个通过!只要我设置了result
的值,它就会失败。
任何帮助,非常感谢。
我的歉意。断言实际上有效,但是当我登录到控制台时,失败。 – Rimian
我想我误解了这个问题。它在'this.set('result',true);'行失败,因为需要运行循环;但由于环境处于测试模式,因此不存在。因此,由于错误,'promise happen 2'永远不会呈现给控制台。我是否错过了srh?这正是我想解释的。对不起,如果我完全错了。 – alptugd