asynFn(url, callback)该函数接受一个url并发出一些xhr请求,然后使用callback(result)将处理的结果发回。我该怎么测试呢?
(我在Chrome中直接运行了asynFn,运行得很好。)
我试图使用jasmine-ajax对请求进行存根处理,但是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
})
})我在这里错过了什么?
发布于 2015-11-23 11:27:22
问题是,asynFn是异步,在执行expect语句后调用回调y。
以为你考得像历史一样。
将代码更改为:
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
});
});https://stackoverflow.com/questions/33869485
复制相似问题