我已经包括了用于登录功能的cookieservice,但是在执行单元测试用例时,它针对每个测试规范显示错误消息没有cookieservice提供程序。是否有一个全局模拟cookieservice的选项,以便它在每个测试规范中调用。请帮帮我
import { CookieService } from '@alfresco/adf-core';
mockService( CookieService, {
getItem: () => '',
setItem: () => {},
})
答案 0 :(得分:0)
执行的单元测试规格独立于其他规格。因此,我们需要为所有规格单独注入所有依赖项。同样,每个执行的单元测试应该是独立的并且应该独立运行,它们不应影响其他测试用例或应受到其他测试用例的影响。 现在要问您的问题,如何创建一个可以为我们在测试平台中初始化的每个模块注入的全局模拟,将不是一个好主意,因为它可能无法正常工作,因为您测试的每个服务可能都没有相同数量的依赖项。相反,我的建议是:
// mocks.ts This can reside at some shared location
export const CookieServiceMock = {
setCookie(): void => undefined
}
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: []
});