如何解决在单个测试规范中模拟服务,并为所有测试规范全局调用该服务Angular单元测试用例
我已经包括了用于登录功能的cookieservice,但是在执行单元测试用例时,它针对每个测试规范显示错误消息没有cookieservice提供程序。是否有一个全局模拟cookieservice的选项,以便它在每个测试规范中调用。请帮帮我
import { CookieService } from '@alfresco/adf-core';
mockService( CookieService,{
getItem: () => '',setItem: () => {},})
解决方法
执行的单元测试规格独立于其他规格。因此,我们需要为所有规格单独注入所有依赖项。同样,每个执行的单元测试应该是独立的并且应该独立运行,它们不应影响其他测试用例或应受到其他测试用例的影响。 现在要问您的问题,如何创建一个可以为我们在测试平台中初始化的每个模块注入的全局模拟,将不是一个好主意,因为它可能无法正常工作,因为您测试的每个服务可能都没有相同数量的依赖项。相反,我的建议是:
- 创建一个通过文件导出的模拟对象(您也可以创建一个类):
// mocks.ts This can reside at some shared location
export const CookieServiceMock = {
setCookie(): void => undefined
}
- 用新的模拟程序注入TestBed
import { CookieServiceMock } from 'mocks.ts'
describe('ServiceToTest',() => {
let serviceToTest: ServiceToTest; // Replace with your service
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
ServiceToTest
// Below line will replace your service with mock and
// needs to be done at all places where cookieService is dependency.
{provide: CookieService,useValue: CookieServiceMock }
//useClass if CookieService mock is a class
//This way you don't need inject the dependencies explicitly for injected
//services.
],imports: []
});
// Get the instance of service to test
serviceToTest = TestBed.get(ServiceToTest);
// This will now return the instance of mock i.e. CookieServiceMock object
cookieService = TestBed.get(CookieService);
});
it('Service to test',()=>{
// Now you can access all the methods to test within your target service
// and also your methods that you want to Spy from your mock.
})
});
另一种方法是,如果您想保留所有测试模块通用的一些配置,那就是:
TestBed.configureTestingModule(
// Extract out this Object.
// But this might not work in most cases since every service or
// component to test have a different dependencies.
{
providers: [],imports: []
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。