模拟可观察对象返回的文档元素

时间:2019-01-15 22:59:19

标签: javascript angular unit-testing

我有一个Observable服务,该服务在html中搜索元素并返回其innerText。我正在尝试模拟元素并通过可观察的返回其值。但是,我一直收到Failed: Cannot read property 'getElementById' of undefined。为什么会这样?

class AuthenticationService {
....
 authenticate(): Observable<boolean> {
    const configText = this.document.getElementById('authentication-config').innerText;
    const parsedValue = JSON.parse(configText);
    const result: boolean = parsedValue.isClient;
    return of(result);
  }
}

以下是我编写的测试

describe('AuthenticationService', () => {
  let document, mockElement: any;
  let authService: AuthenticationService;
  let spy: any;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [],
      providers: [
        { provide: DOCUMENT, useValue: document },
      ]
    });
    document = {}
    mockElement = {}
    document.getElementById = jasmine.createSpy('getElementById');
    document.getElementById.and.returnValue(mockElement);
  });

  it('should return a boolean', async(inject([AuthenticationService], (authUser) => {
    mockElement.innerText = JSON.stringify({ isClient: false });
    authUser.authenticate().subscribe(result => expect(result).toBe(Boolean))
  })));
});

0 个答案:

没有答案