【问题标题】:Angular9 unit-testing: Is it possible to MOCK Parse.initialize and still have reliable tests?Angular9 单元测试:是否可以模拟 Parse.initialize 并且仍然有可靠的测试?
【发布时间】:2020-06-16 16:30:21
【问题描述】:

我想测试组件如何使用我的 Angular Service 中的 Parse.initialize(appId,url) 函数执行此操作?
这是初始化部分:

Parse.initialize('MY_APP_ID', 'JS_KEY');
Parse.serverURL = 'https://parseapi.back4app.com/';

这是我的测试部分:

describe('StateComponent', () => {
  let component: StateComponent;
  let fixture: ComponentFixture<StateComponent>;
  let service: TrayStateService;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [StateComponent],
      providers: [
        TrayStateService,
        { provide: NbDialogService, useValue: {} },
        { provide: NbToastrService, useValue: {} },
        ChangeDetectorRef,
        AuthSessionQuery,
        {
          provide: 'env',
          useValue: environment
        }
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
    service = TestBed.inject(TrayStateService);
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(StateComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should verify that immediate function works properly', fakeAsync(() => {
      spyOn(service, 'getAll').and.returnValue(of(MockedDataResponseArray));
      component.ngOnInit();
      tick(10);
  }));

这是我得到的错误:

错误:您需要在使用 Parse 之前调用 Parse.initialize。

【问题讨论】:

    标签: angular unit-testing mocking parse-javascript-sdk


    【解决方案1】:

    您可以通过直接指派提供间谍。

    let backup: any;
    beforeEach(() => {
      backup = Parse.initialize;
      Parse.initialize = jasmine.createSpy();
    });
    afterEach(() => Parse.initialize = backup);
    
    // ... your normal code
    
    it('in a test', () => {
      // ... your normal code
      expect(Parse.initialize).toHaveBeenCalledWith('MY_APP_ID', 'JS_KEY');
      expect(Parse.serverURL).toEqual('https://parseapi.back4app.com/');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 2017-03-20
      • 1970-01-01
      • 2013-10-17
      • 1970-01-01
      相关资源
      最近更新 更多