[英]How to mock Logger in jest
我该如何开玩笑地模拟 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.