我正在使用node.js
开发一个nestjs
应用程序
我有一个名为LoggerService
的类,如下所示:
export class LoggerService {
private logger: Rollbar;
constructor() {
this.logger = this.setupLogger();
}
critical(...args: Array<string | Error | object | Date | any[]>) {
this.logger.error(...args);
}
private setupLogger(): Rollbar {
if (this.logger == null) {
this.logger = new Rollbar({
accessToken: 'token',
environment: 'dev',
captureUncaught: true,
captureUnhandledRejections: true,
});
}
return this.logger;
}
现在,我正在使用下面的玩笑为此类编写单元测试。
describe('LoggerService.log', () => {
let service: LoggerService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [LoggerService],
}).compile();
service = module.get<LoggerService>(LoggerService);
});
it('critical', () => {
service.critical('error','message');
expect(???).toHaveBeenCalledWith('error', 'message')
})
);
我的问题是如何检查(期望)是否调用logger.error
,或如何在此类中模拟Rollbar
。
答案 0 :(得分:1)
1)提供您的外部依赖关系/库作为模块中的可注入令牌
from typing import Dict, List, TextIO
def read_grades(gradefile: TextIO) -> Dict[float, List[str]]:
"""Read the grades from gradefile and return a dictionary where each key is a grade and each value is the list of ids of students who earned that grade.
Precondition: gradefile starts with a header that contains no blank lines, then has a blank line, and then lines containing s dtudent number and a grade.
"""
# skip over the header
line = gradefile.readline()
while line != 'n/':
line = gradefile.readline()
# read the grades, accumulating them into a dict
grade_to_ids = {}
line = gradefile.readline()
while line != '':
student_id = line[:4]
grade = float(line[4:].strip())
if grade not in grade_to_ids:
grade_to_ids[grade] = [student_id]
else:
grade_to_ids[grade].append(student_id)
line = gradefile.readline()
return grades_to_ids
2)将其注入您的@Module({
providers: [
{
provide: 'Rollbar',
useFactory: async (configService: ConfigService) => new Rollbar({
accessToken: configService.accessToken,
environment: configService.environment,
captureUncaught: true,
captureUnhandledRejections: true,
}),
inject: [ConfigService],
},
]
中,而不是创建它
LoggerService
3)现在,您可以在测试中模拟依赖项
export class LoggerService {
constructor(@Inject('Rollbar') private logger: Rollbar) {
}