asynFn(url, callback)
此函数接受一个 url 并触发一些 xhr 请求,然后使用 callback(result)
发送回处理后的结果。我应该如何测试它?
(我直接在 Chrome 中运行了 asynFn
,它运行良好。)
我尝试使用 jasmine-ajax
来 stub 请求,但是 expect
没有工作。
describe('a test', function() {
var callback
beforeAll(function() {
jasmine.Ajax.install()
jasmine.Ajax.stubRequest('fake/path1').andReturn({
status: 200,
contentType: 'text/plain',
responseText: 'yay'
})
jasmine.Ajax.stubRequest('fake/path2').andReturn({
status: 200,
contentType: 'text/plain',
responseText: 'yay2'
})
// ...
})
afterAll(function() {
jasmine.Ajax.uninstall()
})
beforeEach(function() {
callback = jasmine.createSpy('sendResponse')
})
it('a spec', function() {
asynFn('input string', callback)
expect(jasmine.Ajax.requests.mostRecent().url).toBe('fake/path2')
expect(callback).toHaveBeenCalled() // faild
})
})
我在这里错过了什么?
最佳答案
问题是asynFn是异步,在expect语句执行完后调用的回调y。
认为您的测试就像历史。
- 正在测试的对象(描述)
- asynFn 执行时(beforeEach)
- 然后:应该调用一个方法或回调 (it)
将您的代码更改为:
beforeEach(function() {
callback = jasmine.createSpy('sendResponse');
asynFn('input string', callback);
});
afterEach(function() {
callback = null;
});
it('a spec', function() {
expect(jasmine.Ajax.requests.mostRecent().url).toBe('fake/path2')
expect(callback).toHaveBeenCalled() // faild
})
如果第一个不起作用,试试这个:
beforeEach(function(done) {
callback = jasmine.createSpy('sendResponse');
asynFn('input string', function() {
callback();
done(); //<-- This tells jasmine tha async beforeEach is finished
});
});
关于javascript - 不知道如何用 Jasmine 测试这个异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33869485/