[英]Unable to test Angular service with Console constructor parameter
我正在嘗試實現名稱服務所暗示的日志記錄服務。 日志服務的具體實現將在初始化時解決。 這個具體的實現是使用控制台來記錄消息。 我需要構造函數中的Console
能夠在不影響全局console
對象的情況下模擬它。
我在 Jasmine 上進行了相同的測試,它會通過的很好。 它在應用程序中也運行良好,所以我認為它與 Jest 或其配置有關。
我正在嘗試將控制台接口注入到我的 Angular 服務中,如下所示:
export class ConsoleLoggerService implements LoggerService {
constructor(public console: Console) { }
}
當我嘗試運行我的測試時:
describe('ConsoleLoggerService', () => {
let service: ConsoleLoggerService;
let consoleMock: Console;
beforeEach(async(() => {
consoleMock = {
log(message?: any, ...optionalParams: any[]) { }
} as Console;
service = new ConsoleLoggerService(consoleMock);
}));
it('should be created', () => {
expect(service).toBeTruthy();
});
});
我收到這個錯誤
● Test suite failed to run
ReferenceError: Console is not defined
9 | export class ConsoleLoggerService implements LoggerService {
10 |
> 11 | constructor(public console: Console) { }
| ^
在我的理解中, Console
接口來自@types/node
並且應該在全球范圍內可用。 為什么我的測試失敗了?
我的工作區使用的是 Angular 9、Jest 24.9 和 Nx 9。
如果您想測試控制台日志是否被點擊,請使用 jest 來模擬它。 在您的測試中,您可以執行以下操作:
it('console.log the text "hello"', () => {
console.log = jest.fn();
// call some function here that will end up doing your logging
// The first argument of the first call to the function was 'hello'
expect(console.log.mock.calls[0][0]).toBe('hello');
});
如果你只是為了測試目的而注入它,我會建議你像上面一樣使用 jest 來模擬它。
如果您必須像這樣繼續注入它,您可以使用測試平台來提供一個虛假的提供者:
beforeEach(() => {
TestBed.configureTestingModule({
// MockConsole would be some fake class that you create
providers: [{provide: Console, useClass: MockConsole }]
});
service = TestBed.get(CgonsoleLoggerService);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.