[英]Mocking a service in single test spec and call it globally for all test specs Angular unit test case
我已经包含了用于登录功能的 cookieservice,但是在执行单元测试用例时,它显示错误消息No provider for cookieservice for each test specs。 是否有一个选项可以全局模拟 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
}
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: []
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.