如何使用Jasmine模拟chrome.cookies.getAll?

时间:2019-05-16 11:57:10

标签: javascript unit-testing google-chrome-extension jasmine stub

我在background.js中有以下代码


var allCookies = [];
function getAllCookies() {
   chrome.cookies.getAll({}, function(cookies) {
    for (var i in cookies) {
      allCookies.push(cookies[i])
     }
    }
   });
}

现在在specs.js中,我编写了以下代码来测试getAllCookies方法-


describe('getAllCookies', function() {
    beforeEach(function() {
      chrome = {
        cookies: {
            getAll : function() { 
                return [
                    'cookie1',
                    'cookie2'
                ]
            }
        }
      };
      spyOn(chrome.cookies,'getAll');
    });
    it('should updated global variable allCookies', function() {
      getAllCookies();
      expect(allCookies).toEqual(['cookie1','cookie2'])
    })
  })

但是测试失败,为allCookies = [],但应等于['cookie1','cookie2']

有人可以帮我模拟使用回调函数作为参数的chrome API(例如chrome.cookies.getAll)吗?

0 个答案:

没有答案