【问题标题】:Angular + Jasmine, move test to the common module. Service -> undefinedAngular + Jasmine,将测试移至通用模块。服务->未定义
【发布时间】:2018-11-26 08:17:33
【问题描述】:

我拿了常用模块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来到了公共模块。

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

【问题讨论】:

    标签: javascript angular jasmine


    【解决方案1】:

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

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

    【讨论】:

    • 按照您的建议尝试 - 同样的错误:无法读取未定义的属性“注销”
    • 为什么globals.relogin(globals.user, authService); 不在测试套件中?
    • 这是一套常用的测试,我想在其他人中重用 *.spec.ts
    • 好的,没关系,但是如果globals.relogin(globals.user, authService); 不在测试套件中,这意味着它没有可用的服务注入实例,因为它被注入到it() 套件中。跨度>
    • globals.relogindescribe('AdvertService', () => { let authService: AuthService;... globals.relogin(, authService)}); 内部,服务对象应该可以看到,不是吗?
    猜你喜欢
    • 2017-08-19
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    相关资源
    最近更新 更多