TypeScript - ใช้ Jasmine custom matcher กับโปรเจกต์ Angular CLI
ฉันมีความต้องการอย่างง่าย: ต้องการใช้ matcher แบบกำหนดเองของฉันใน unit test ของ Jasmine ภายในโปรเจกต์ Angular CLI (Angular v6) มีข้อจำกัดสองสามข้อ:
- ฉันไม่ต้องการแก้ไขอะไรภายใต้โฟลเดอร์ node_modules; โปรเจคนี้ต้องสามารถผ่านกระบวนการ build ของฉันซึ่งจะทำการติดตั้งใหม่ทุกครั้ง
- ฉันไม่อยากต้องสร้างโมดูล npm แค่เพื่อที่จะสามารถเพิ่มลงใน
typesใน tsconfig.spec.json
สิ่งที่ฉันสามารถสังเกตได้จนถึงตอนนี้คือฉันต้องการไฟล์ .d.ts ดังนั้นนี่คือ matchers.d.ts ของฉัน:
/// <reference path="../../../node_modules/@types/jasmine/index.d.ts" />
declare namespace jasmine {
interface Matchers<T> {
toContainPath(path: string): boolean;
}
}
ในไดเรกทอรีเดียวกัน ฉันมีไฟล์ matchers.ts ของฉัน:
export const customMatchers: jasmine.CustomMatcherFactories = {
// Affirms the element contains a sub-element at the given CSS path.
toContainPath: function (_util, _customEqualityTesters) {
return {
compare: function (element: HTMLElement, path: string) {
const result = {
pass: false,
message: ''
};
if (!element) {
result.message = 'Expected element to be non-empty';
} else if (!path) {
result.message = 'Expected path to be non-empty';
} else {
result.pass = element.querySelector(path) !== null;
result.message =
'Expected ' + element + (result.pass ? ' not' : '') + ' to contain ' + path;
}
return result;
}
};
}
};
ในไฟล์ทดสอบ (spec) ของฉัน ฉันมี:
import { customMatchers } from 'app/testing/matchers';
. . .
/// <reference path="../../../testing/matchers.d.ts" />
. . .
beforeEach(() => {
jasmine.addMatchers(customMatchers);
. . .
และสุดท้าย ฉันใช้ matcher ในการทดสอบที่รวมอยู่ด้วย เช่น:
expect(element).toContainPath('my-sidebar');
ฉันยังพยายามเพิ่มเส้นทางเต็มของ matchers.d.ts เข้าไปในอาเรย์ types ใน tsconfig.spec.json ด้วย
น่าเสียดายที่ผมยังไม่สามารถหาวิธีแก้ปัญหาที่ใช้งานได้ ความล้มเหลวยังคงปรากฏเป็น error TS2339: Property 'toContainPath' does not exist on type 'Matchers
สถานที่ที่ดูน่าสนใจ แต่ก็ไม่มีผล:
- ตัวจับคู่จัสมินแบบกำหนดเอง
- การเพิ่มการกำหนดประเภท TypeScript ของตัวจับคู่ jasmine
- ตัวจับคู่ jasmine
- ทดสอบ Angular ด้วยตัวจับคู่แบบกำหนดเอง
- เพิ่มไฟล์การพิมพ์ลงใน TypeScript ด้วยตนเอง
มีใครสามารถให้สูตรลับได้ไหม?
คำตอบ #1
คำตอบทั้งสองที่รวมกันที่นี่สุดท้ายก็ใช้ได้ผลกับฉัน!
สร้างตัวจับคู่ Jasmine แบบกำหนดเองโดยใช้ Typescript
เพิ่มไฟล์ index.ts ไปที่โฟลเดอร์ทดสอบและทำให้ไฟล์ .ts และ .d.ts มีชื่อที่แตกต่างกัน (เช่น custom-matchers.ts และ matchers-types.d.ts)