如何使用模拟服务在Angular中对(非组件)支持类进行单元测试



我不太清楚如何用Jasmine对Angular中支持类的一些方法进行单元测试。测试中的类是一个单例的纯类型脚本类,它在启动时由其中一个服务初始化,然后在应用程序的生命周期中由各种组件通过调用AccountsManager.getInstance()来使用。

这是这个类的构造函数和初始化器,名为AccountsManager:

export class AccountsManager {
private static instance: AccountsManager;
static initialize(accountService: AccountService) {
if (!this.instance) { this.instance = new AccountsManager(accountService) }
}
static getInstance(): AccountsManager {
if (!this.instance || !this.instance.isInitialized) {
throw new Error("AccountsManager.getInstance(): AccountManager has not been initialized");
}
return this.instance;
}
//methods...
}

我根据各种参考文档中的内容尝试了Jasmine测试的设置,但我看到的文档显示了如何测试Angular组件,而不是任意类。

问题是获取用于初始化AccountsManager的AccountService实例。实例化真正的AccountService很复杂,所以我想使用模拟服务,因为我想运行的单元测试无论如何都不依赖于AccountService。

我找到了一个如何用模拟服务测试组件的例子,但我猜它们是测试POTC的错误设置

不管怎样,这就是我尝试的,只是为了看看。

fdescribe('AccountsManager', () => {
let fixture: ComponentFixture<AccountsManager>
let mockAccountService = {  }
let component : AccountsManager;
beforeEach(() =>{
TestBed.configureTestingModule({
declarations: [AccountsManager],
providers: [{provide: AccountService, useValue:  mockAccountService}]
})
fixture= TestBed.createComponent(AccountsManager);
component = fixture.componentInstance;
})
});

我猜这永远不会起作用,因为"AccountsManager"只是一个类,它不是Angular组件,但无论如何,它现在在TestBed.createComponent(AccountsManager)上失败了,并显示错误消息,AccountsManageer的构造函数是私有的(按设计(,createComponent希望有一个公共构造函数。但我猜还有一种更直接的方法可以做我想做的事。

如果我只想用一个伪AccountsService实例初始化这个类,那么最简单的方法是什么?

如果我得到了你想要的,你需要这样的东西:

describe('AccountsManager', () => {
let mockAccountService = {};
let accountsManager: AccountsManager;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{provide: AccountService, useValue:  mockAccountService}]
});
AccountsManager.initialize(TestBed.inject(AccountService));
accountsManager = AccountsManager.getInstance();
});
it('should be a singleton', () => {
AccountsManager.initialize(TestBed.inject(AccountService));
const am = AccountsManager.getInstance();
expect(am === accountsManager)
.withContext('AccountsManager is not a singleton')
.toBeTrue();
});
});

最新更新