javascript - 如何开玩笑地模拟 Logger
问题描述
我该如何嘲笑 Logger 方法/实例?我确实尝试了在线资源,但找不到任何有用的东西。有人可以帮帮我吗?只是模拟记录器方法就足够了。我能够模拟其他代码。因此,我无法测试错误条件。
import rp from "request-promise-native";
import BookLogger from "Book-logger";
const logger = BookLogger.getLogger('Book-service', BookLogger.LOG_LEVEL.INFO);
export class BookService {
@param bookCategory id of book category
@param boooks list of books
public static async getAllBookInCategory(bookCategory: string) {
try {
const neededInfo = {
url: `https://${process.env.BOOK_HOST}/bookapi/${process.env.BOOKAPI_VERSION}/iterative/bookCategory/${ bookCategory }/books/all `,
method: 'GET',
}
const result = await BookService.makeRequest(bookCategory, neededInfo);
return await rp(result);
} catch(error) {
logger.error(`Failed to get All Books in given category ${error}`)
}
}
解决方案
这是解决方案:
main.ts
:
import BookLogger from './Book-logger';
const logger = BookLogger.getLogger('Book-service', BookLogger.LOG_LEVEL.INFO);
export function main() {
const error = new Error('Internal server error');
logger.error(`Failed to get All Books in given category ${error}`);
}
Book-logger.ts
:
export default class BookLogger {
public static LOG_LEVEL = {
INFO: 'INFO',
};
public static getLogger(name, level) {
return {
error: (message) => {
console.error(message);
},
};
}
}
main.test.ts
:
import { main } from './main';
import BookLogger from './Book-logger';
jest.mock('./Book-logger.ts', () => {
const mLogger = {
error: jest.fn(),
};
return {
LOG_LEVEL: require.requireActual('./Book-logger.ts').default.LOG_LEVEL,
getLogger: jest.fn(() => mLogger),
};
});
describe('main', () => {
afterEach(() => {
jest.resetAllMocks();
});
it('should mock logger correctly', () => {
const logger = BookLogger.getLogger('Book-service', BookLogger.LOG_LEVEL.INFO);
main();
expect(jest.isMockFunction(logger.error)).toBeTruthy();
const error = new Error('Internal server error');
expect(logger.error).toBeCalledWith(`Failed to get All Books in given category ${error}`);
});
});
带有覆盖率报告的单元测试结果:
PASS src/stackoverflow/59366107/main.test.ts
main
✓ should mock logger correctly (4ms)
----------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------|----------|----------|----------|----------|-------------------|
All files | 83.33 | 100 | 50 | 81.82 | |
Book-logger.ts | 71.43 | 100 | 33.33 | 66.67 | 6,8 |
main.ts | 100 | 100 | 100 | 100 | |
----------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.562s, estimated 11s
源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59366107
推荐阅读
- c# - Xamarin Forms 中的调试错误(应用程序正在模拟器中部署)
- android - 我的应用程序不符合使用请求的权限 Google 新政策的条件
- c - 没有 -fPIC 的全局变量的位置
- integer - 整数的反转数字——相似的代码不同的输出
- logstash - 在 Logstash 中转换多维数组
- javascript - Angular 7 使用 *ngfor 对数据进行分组
- linux - 如果第一个单元格的值满足条件,如何从 CSV 中删除一行?
- python - Python监控radiusd服务。负载均衡器 tcp 健康检查
- c++ - 公式与指定值不匹配的 C++ 结果
- javascript - 使用模板替换 https 链接