ค้นหาเว็บไซต์

javascript - ฉันจะเพิ่มการกำหนดชนิดของตัวจับคู่แบบกำหนดเองของ Jasmine ใน Typescript ได้อย่างไร?


ฉันได้หาดูรอบ ๆ และคำถามนี้ดูเหมือนจะเป็นเรื่องที่เกิดซ้ำบ่อย อย่างไรก็ตาม ไม่มีวิธีแก้ไขใดที่ฉันเจอที่ดูเหมือนจะใช้ได้ผลกับฉัน

ใช้ดังต่อไปนี้:

{
  "typescript": "2.3.2",
  "jasmine-core": "2.6.1",
  "@types/jasmine": "2.5.47"
}

ฉันไม่สามารถทำให้ Typescript รวมการประกาศ namespace ที่มีการกำหนด matcher แบบกำหนดเองของฉันได้

เพิ่มสิ่งนี้:

declare namespace jasmine {
  interface Matchers<T> {
    toBeAnyOf(expected: jasmine.Expected<T>, expectationFailOutput?: any): boolean;
  }
}

ซ่อนทุกประเภทอื่นที่ประกาศไว้ก่อนหน้านี้บน jasmine คอมไพเลอร์จะแสดงข้อผิดพลาดเช่น:

[ts] Namespace 'jasmine' has no exported member 'CustomMatcherFactories'
[ts] Namespace 'jasmine' has no exported member 'CustomMatcher'.

มีวิธีที่เหมาะสมในการเพิ่ม matcher แบบกำหนดเองและทำให้มันทำงานร่วมกับ Typescript ได้อย่างราบรื่นหรือไม่?

มีปัญหาเพิ่มเติมกับ tslint หากคุณกำลังใช้ชุดกฎ tslint:recommended กฎเหล่านั้นจะไม่อนุญาตให้ใช้คีย์เวิร์ด namespace หรือ module ดังนั้นผมจึงต้องปิดตัวตรวจสอบโค้ด (หรือเปลี่ยนกฎ "no-namespace") เพื่อที่จะลองสิ่งนี้ ไม่แน่ใจว่าคนอื่นจะทำอย่างไรเพื่อขยายคำนิยามหากสิ่งนี้ถือว่า "ไม่แนะนำ"

คำตอบ #1

ฉันต้องแก้ไขไฟล์สามไฟล์เมื่อฉันเพิ่มตัวจับคู่แบบกำหนดเอง ฉันสร้างไฟล์ชื่อ matchers.ts ที่ประกอบด้วยตัวจับคู่จริง ๆ ของฉัน จากนั้นฉันได้เพิ่มการนำเข้าไปยัง test.ts สำหรับไฟล์ matchers.ts ของฉัน สุดท้าย ฉันได้เพิ่มอินเตอร์เฟสไปยังไฟล์ typings.d.ts ซึ่งประกอบด้วยตัวจับคู่ของฉัน

matchers.ts (ชื่อสุ่ม)

beforeEach(() => {
    jasmine.addMatchers({
        toContainText: () => {
            return {
                compare: (actual: HTMLElement, expectedText: string, customMessage?: string) => {
                    const actualText = actual.textContent;
                    return {
                        pass: actualText.indexOf(expectedText) > -1,
                        get message() {
                            let failureMessage = 'Expected ' + actualText + ' to contain ' + expectedText;

                            if (customMessage) {
                                failureMessage = ' ' + customMessage;
                            }

                            return failureMessage;
                        }
                    };
                }
            };
        },
    });
});

test.ts

import 'test/test-helpers/global/matchers'; (my relative filepath)

typings.d.ts

declare module jasmine {
  interface Matchers {
    toContainText(text: string, message?: string): boolean;
  }
}

บทความที่เกี่ยวข้อง