Jasmine测试设置组件变量

时间:2017-05-24 12:26:32

标签: javascript angular karma-jasmine

我在茉莉花测试中使用spyOn来“监听”来自服务的函数调用,

该函数返回一个Observable。

我收到错误意外令牌U JSON;

错误是从组件行生成的:

this.config = JSON.parse(localStorage.getItem('configuration'));

localStorage项目是JSON.stringified;

据我所知,当JSON.parse = undefined,

时,通常会抛出此错误

所以我试着在我的测试中设置变量,即

component.config =  mockConfig;

所以..

 // Storage Mock
  function storageMock() {
    var storage = {};
      return {
      setItem: function(key, value) {
        storage[key] = value || '';
      },
      getItem: function(key) {
        return key in storage ? storage[key] : null;
      },
      removeItem: function(key) {
        delete storage[key];
      },
      get length() {
        return Object.keys(storage).length;
      },
      key: function(i) {
        var keys = Object.keys(storage);
        return keys[i] || null;
      }
    };
  }
  let mockConfig = JSON.stringify({
    base_url:"http://image_url/",
    poster_sizes:['w9', 'w100']
  })
  //Set storage
 let m =  storageMock()
 m.setItem('configuration', mockConfig)

  it('Should set items array with values from MoviesService', () => {
    component.config = JSON.parse(m.getItem('configuration'));
       let spy = spyOn(moviesService, 'getPreview').and.callFake(()=>{
        return Observable.from([[{id1: 1, title: 'a'}, {id1: 2, title: 'b'}]])
  })
  component.ngAfterViewInit();
  expect(component.items.length).toBeGreaterThan(0);
});

1 个答案:

答案 0 :(得分:2)

对于遇到此问题的任何人,我通过将此代码放在beforeEach包装器中来完成此工作

Object.defineProperty(window, 'localStorage', { value: m });

基本上它使用我的mock localStorage变量而不是window对象中的变量。