Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 角度(8)-具有专用变量的单元测试服务_Angular_Unit Testing_Karma Jasmine - Fatal编程技术网

Angular 角度(8)-具有专用变量的单元测试服务

Angular 角度(8)-具有专用变量的单元测试服务,angular,unit-testing,karma-jasmine,Angular,Unit Testing,Karma Jasmine,我想知道我正在构建和测试的服务的方法是否正确。我总是将我的类设计为尽可能的封装。所以,在构建角度服务时,我也用同样的方式构建它们 以下是我的服务的外观片段: private postUrl='2〕https://localhost:44359/api/posts'; private currentGetPostsUrl=`${this.postrl}?page=${this.pageNumber}&pageSize=${this.pageSize}`; private filteredPostL

我想知道我正在构建和测试的服务的方法是否正确。我总是将我的类设计为尽可能的封装。所以,在构建角度服务时,我也用同样的方式构建它们

以下是我的服务的外观片段:

private postUrl='2〕https://localhost:44359/api/posts';
private currentGetPostsUrl=`${this.postrl}?page=${this.pageNumber}&pageSize=${this.pageSize}`;
private filteredPostListSource=新主题();
filteredPostList$=this.filteredPostListSource.asObservable();
//从api返回的post列表
private originalPostList:IPostViewDto[];
//显示给用户的筛选列表
private filteredPostList:IPostViewDto[];
//获取已分页的帖子列表
getPosts():可观察{
const urlToFetch=`${this.postrl}?page=${this.pageNumber}&pageSize=${this.pageSize}`;
//如果帖子列表存在,则返回该帖子列表
如果(此原始邮件列表){
返回(此原始邮件列表);
}
返回this.http.get(urlToFetch,{observe:'response'})
.烟斗(
map((响应:HttpResponse)=>{
const paginationHeader=JSON.parse(response.headers.get('X-Pagination');
this.totalCount=paginationHeader.totalCount;
this.originalPostList=response.body;
this.filteredPostList=[…this.originalPostList];
返回响应.body;
}),
catchError(err=>this.errorHandler(err))
);
}
如上所述,我不允许组件直接访问私有变量,而是使用方法来完成所有交互。这里的问题是单元测试有点混乱。如果我想正确地测试我的
getPosts()
方法是否正确地返回我的
originalPostList
中的帖子列表(如果它存在),我必须在为http get创建存根值后运行一次,以确保设置了私有字段,然后再次运行它并比较我的存根值是否等于第二次运行的
getPosts()

这似乎不仅是一个糟糕的单元测试,而且可能服务本身没有正确构建以进行测试

什么是最好的方法来重新构造它,使其易于测试?我只是创建getter/setter并测试它们吗?或者我上面描述的方法有效吗



请注意,我以这种方式设计它的原因是,我不希望子组件/其他组件在没有显式方法调用的情况下意外更新这些属性(这样我就可以编写测试来确保这种情况)。这并不是因为只有一个组件访问此服务。

我同意您不应该在测试中访问私有变量。如果您这样做了,那么当您需要进行重构时,您的测试将毫无用处


我认为在测试中两次调用该方法没有问题。我假设它将发生在实际代码中,因为您正在实现缓存机制。“您的测试越像您的软件的使用方式,它们就越能给您带来信心。”

您可以创建用于访问私有变量的getter方法,也可以将其更改为public并向其添加
只读
。这样,其他组件/测试可以访问它,但无法更改它

在我看来,您不应该两次调用方法来测试它们。根据您的示例,我可能会创建一个接受GET参数的函数。一旦有了这些,您就可以通过HttpClientTestingModule测试是否命中了正确的API端点并获得了正确的数据对象