ProgramingTip

속성의 하위 집합에서 개체를 비교하는 재스민 매 처가하는?

bestdevel 2020. 11. 17. 20:40
반응형

속성의 하위 집합에서 개체를 비교하는 재스민 매 처가하는?


테스트중인 내 동작에 따라 확장 될 수있는 개체가있을 것입니다.

var example = {'foo':'bar', 'bar':'baz'}

var result = extendingPipeline(example)
// {'foo':'bar', 'bar':'baz', 'extension': Function}

expect(result).toEqual(example) //fails miserably

이 경우 다음과 같이 통과 할 매처를 갖고 싶습니다.

expect(result).toInclude(example)

사용자 지정 매처를 이미 해결 방법이있을 것입니다. 어디에서 찾아야?


재스민 2.0

expect(result).toEqual(jasmine.objectContaining(example))

이 수정 사항 이후 : https://github.com/pivotal/jasmine/commit/47884032ad255e8e15144dcd3545c3267795dee0 중첩 된 개체를 사용하여 부분적으로 일치하는 각 개체를 래핑하면됩니다.jasmine.objectContaining()

간단한 예 :

it('can match nested partial objects', function ()
{
    var joc = jasmine.objectContaining;
    expect({ 
        a: {x: 1, y: 2}, 
        b: 'hi' 
    }).toEqual(joc({
        a: joc({ x: 1})
    }));
});

나는 같은 문제가 있었다. 나는 방금이 코드를 시도했지만 나를 위해 작동합니다.

expect(Object.keys(myObject)).toContain('myKey');

나는 그것이 그렇게 일반적이라고 생각하지 당신이 하나를 사용한다고 생각하지 않습니다. 하나만 작성하십시오.

beforeEach(function () {
    this.addMatchers({
        toInclude: function (expected) {
            var failed;

            for (var i in expected) {
                if (expected.hasOwnProperty(i) && !this.actual.hasOwnProperty(i)) {
                    failed = [i, expected[i]];
                    break;
                }
            }

            if (undefined !== failed) {
                this.message = function() {
                    return 'Failed asserting that array includes element "'
                        + failed[0] + ' => ' + failed[1] + '"';
                };
                return false;
            }

            return true;
        }
    });
});

나는 현대 자바 펼쳐 맵과 휴식 연산자를 사용하여 대안을 제공 할 생각했습니다. 나머지 연산자와 함께 비 구조화를 사용하여 속성을 생략 할 수 있습니다. 이 기사의 추가 설명을 참조하십시오 .

var example = {'foo':'bar', 'bar':'baz'}

var { extension, ...rest } = extendingPipeline(example)

expect(rest).toEqual(example)

참고 URL : https://stackoverflow.com/questions/15322793/is-there-a-jasmine-matcher-to-compare-objects-on-subsets-of-their-properties

반응형