您好,登錄后才能下訂單哦!
在 Jest 框架中測(cè)試依賴注入,首先需要了解依賴注入的概念。依賴注入是一種設(shè)計(jì)模式,用于降低代碼之間的耦合度,提高代碼的可維護(hù)性和可測(cè)試性。在 TypeScript 或其他支持類型的語(yǔ)言中,依賴注入通常通過(guò)構(gòu)造函數(shù)、屬性或方法參數(shù)傳遞依賴關(guān)系。
以下是使用 Jest 測(cè)試依賴注入的示例:
npm install --save-dev jest ts-jest @types/jest
tsconfig.json
以支持 Jest:{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"strict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"skipLibCheck": true,
"moduleResolution": "node"
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
MessageService
接口和一個(gè)實(shí)現(xiàn)該接口的 EmailService
類:// src/message-service.ts
export interface MessageService {
sendMessage(to: string, content: string): void;
}
// src/email-service.ts
import { MessageService } from "./message-service";
export class EmailService implements MessageService {
sendMessage(to: string, content: string) {
console.log(`Sending email to ${to}: ${content}`);
}
}
NotificationService
類:// src/notification-service.ts
import { MessageService } from "./message-service";
export class NotificationService {
constructor(private messageService: MessageService) {}
notify(to: string, content: string) {
this.messageService.sendMessage(to, content);
}
}
NotificationService
的 Jest 測(cè)試:// src/notification-service.test.ts
import { NotificationService } from "./notification-service";
import { MessageService } from "./message-service";
import { EmailService } from "./email-service";
describe("NotificationService", () => {
let notificationService: NotificationService;
let messageService: MessageService;
beforeEach(() => {
messageService = new EmailService();
notificationService = new NotificationService(messageService);
});
it("should send a message using the provided message service", () => {
const sendMessageSpy = jest.spyOn(messageService, "sendMessage");
notificationService.notify("user@example.com", "Hello!");
expect(sendMessageSpy).toHaveBeenCalledWith("user@example.com", "Hello!");
});
});
在這個(gè)示例中,我們使用 Jest 的 spyOn
方法來(lái)監(jiān)視 messageService.sendMessage
方法的調(diào)用。然后,我們調(diào)用 notificationService.notify
方法并驗(yàn)證 sendMessage
是否被正確調(diào)用。
要運(yùn)行測(cè)試,請(qǐng)?jiān)?package.json
文件中添加以下腳本:
{
"scripts": {
"test": "jest"
}
}
然后運(yùn)行 npm test
。這將運(yùn)行 Jest 測(cè)試并顯示結(jié)果。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。