自訂物件格式化器

您可以透過定義自訂的物件格式化器,自訂 Jasmine 在配對失敗訊息中描述物件的方式。自訂物件格式化器只是一個函式,如果它知道如何描述物件,就會傳回一個字串;如果不知道,就會傳回 undefined

例如,以下是蘇多庫遊戲的一個測試,其中儲存格建模為具有 expectedcorrectValue 屬性的物件

it('compares some cells', function() {
    const expectedCells = [
        {correctValue: 4, entry: null},
        {correctValue: 1, entry: {pencil: true, numbers: [1, 2]}},
        {correctValue: 5, entry: {pencil: false, number: 3}}
    ];
    const actualCells = [
        {correctValue: 4, entry: null},
        {correctValue: 1, entry: {pencil: false, number: 2}},
        {correctValue: 5, entry: {pencil: false, number: 4}}
    ];

    expect(actualCells).toEqual(expectedCells);
});

這個規範將會失敗,並顯示以下訊息

Expected $[1].entry to have properties
    numbers: [ 1, 2 ]
Expected $[1].entry not to have properties
    number: 2
Expected $[1].entry.pencil = false to equal true.
Expected $[2].entry.number = 4 to equal 3.

您可以透過定義一個自訂物件格式化器,來改善輸出的內容,知道如何格式化儲存格。如果值不是儲存格,則會傳回 undefined。

function formatCell(val) {
    if (val.hasOwnProperty('entry') && val.hasOwnProperty('correctValue')) {
        const entries = val.entry.pencil
            ? 'pencil entries: ' + val.entry.numbers.join(',')
            : 'entry: ' + val.entry.number;

        return '<cell ' + entries + ', correct: ' + val.correctValue + '>';
    }
}

接著,在 beforeEach 中註冊自訂物件格式化器,讓 Jasmine 認識它。

beforeEach(function() {
    jasmine.addCustomObjectFormatter(formatCell);
});

現在,每當儲存格顯示在配對失敗訊息中時,Jamsine 便會使用自訂物件格式化器

Expected $[1] = <cell entry: 2, correct: 1> to equal <cell pencil entries: 1,2, correct: 1>.
Expected $[2] = <cell entry: 4, correct: 5> to equal <cell entry: 3, correct: 5>.

請注意,若要使用自訂物件格式化器,自訂配對器 必須使用 MatchersUtil#pp 來針對其失敗訊息格式化預期的值和實際的值,或允許 Jasmine 透過傳回沒有 message 屬性的結果物件來產生訊息。

jasmine.addMatchers({
    // OK: Jasmine will format expected and actual correctly.
    toBeFoo: function (matchersUtil) {
        return {
            compare: function (actual, expected) {
                return {
                    pass: matchersUtil.equals(actual, expected)
                };
            }
        }
    },

    // OK: Uses pp to format expected and actual.
    toBeBar: function (matchersUtil) {
        return {
            compare: function (actual, expected) {
                return {
                    pass: matchersUtil.equals(actual, expected),
                    message: 'Expected ' + matchersUtil.pp(actual) + ' to be bar like ' + 
                        matchersUtil.pp(expected)
                };
            }
        }
    },

    // Won't use custom object formatters.
    toBeBaz: function (matchersUtil) {
        return {
            compare: function (actual, expected) {
                return {
                    pass: matchersUtil.equals(actual, expected),
                    message: 'Expected ' + actual + ' to be baz like ' + expected
                };
            }
        }
    }
});