Angular + Jasmine,将测试移至通用模块。服务->未定义

时间:2018-11-26 08:17:33

标签: javascript angular jasmine

我参加了通用模块globals.js中的常用测试:

const user = {
  username: 'Skat',
  password: '123',
  role: 'user',
};

function relogin(user, authService) {
  describe('--> relogin', () => {
    it('--> ' + user.role + ', ' + user.username, async () => {
      authService.logout();
      expect(authService.isLogged()).toBe(false);
      authService.login(user.username, user.password).subscribe();
      await delay(800);
      expect(authService.isLogged()).toBe(true);
    });
  });
}

module.exports.user = user;
module.exports.relogin = relogin;

service.spec.ts调用共享测试:

const globals = require('../globals');

describe('AdvertService', () => {
  let authService: AuthService;

  beforeEach(() => {
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000;

    TestBed.configureTestingModule({
      imports: [HttpClientModule, RouterTestingModule],
      providers: [
        AuthService
      ],
    });
  });

  it('Injected services should be created', inject([AuthService], async (authService1: AuthService) => {
      expect(authService).toBeFalsy();
      authService = authService1;
      expect(authService).toBeTruthy();
    }
  ));

  globals.relogin(globals.user, authService);

});

结果,由于以下原因,通用模块的测试失败:

  

TypeError:无法读取未定义的属性“注销”

test fail printscreen

但是由于某种原因undefined进入了通用模块,所以肯定创建了服务对象。

请告诉我如何在测试中通过服务对象,该对象在公共模块中移动?

1 个答案:

答案 0 :(得分:0)

尝试首先告诉您的测试用例异步,然后注入您的服务。像这样:

it('Injected services should be created', async(inject([AuthService], (authService1: AuthService) => {
      expect(authService).toBeFalsy();
      authService = authService1;
      expect(authService).toBeTruthy();
    }
)));