【发布时间】:2021-03-26 21:22:00
【问题描述】:
我以前写过 Angular 测试,但我不知道如何创建一个涵盖以下代码的测试。我将包括我连接的内容,但测试是基本的。
这里是服务文件:
@Injectable()
export class HealthViewService {
constructor(private readonly healthService: HealthService, private router: Router){}
createNewPatient() {
this.healthService.currentStatus = this.healthService.getInitialStatus();
this.router.navigate('health/patient');
}
}
这是规范文件:
import {HealthViewService} from '<not showing pathway>';
import {HealthService} from '<not showing pathway again>';
const healthViewService = {
createNewPatient: () => {}
}
const healthServiceStub = { currentStatus: () { return StatusTarget.Inbound; }}
let routerStub = { navigate: () => {} }
describe('HealthViewService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{provide: Router, useValue: routerStub },
{provide: HealthService, useValue: healthServiceStub },
{provide: HealthViewService, useValue: healthViewService}]
})
});
describe('createNewPatient', () => {
it('it should route to patient page', () => {
expect(healthViewService.createNewPatient).toBeTruthy();
});
});
});
好消息是这个测试通过了,但它并不是一个很好的代码覆盖测试。我的问题是:有什么方法可以正确地模拟路由器并观察路由器导航的位置吗?我可以监视 HealthService 以检查那里的值吗?任何帮助将不胜感激。
【问题讨论】:
-
angular.io/guide/testing 包含涵盖许多不同场景的文章。
标签: angular unit-testing angular8