javascript - วิธีจำลอง Logger ใน jest
ฉันจะล้อเลียนวิธี/อินสแตนซ์ของ 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}`)
}
}
คำตอบ #1
นี่คือวิธีแก้ปัญหา:
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
