>  기사  >  웹 프론트엔드  >  Jest 요약: 전역 객체의 속성과 메서드를 안전하게 모의

Jest 요약: 전역 객체의 속성과 메서드를 안전하게 모의

WBOY
WBOY원래의
2024-07-19 15:10:32305검색

Jest Recap: Safely Mock Properties and Methods of Global Objects

요약:

  • 재정의/모의 속성/메서드가 다른 테스트에 영향을 미치는 것을 방지하고 싶습니다.
  • 로컬 개체(이 테스트에서 생성 및 소유)의 경우 다음을 사용할 수 있습니다(그리고 사용해야 합니다).
    • localObject.theAnswer = 42 및
    • localObject.calcTheAnswer = jest.fn(() => 42).
  • 전역 개체의 경우 사용해야 합니다.
    • jest.replaceProperty(globalObject, "theAnswer", 42) 및
    • jest.spyOn(globalObject, "calcTheAnswer").mockReturnValue(42).
  • jest.restoreAllMocks()가 afterEach() 후크에서 호출되는지 확인하세요.

무엇?

완벽한 세계 코드베이스에서는 전역 객체를 조작할 필요가 없지만 세계 코드베이스는 지저분합니다. 테스트중입니다.

무슨 일이 있어도 피하고 싶은 것은 한 테스트가 다른 테스트에 영향을 미치는 것입니다. 테스트는 순서나 일부 테스트를 건너뛰는 여부에 관계없이 의미가 있어야 합니다.

모의 속성

모의 값에 대한 순진한 접근 방식은 속성을 테스트에 필요한 값으로 설정하는 것입니다.
이 특정 테스트에서 소유한(생성한) 로컬 개체의 값을 변경하는 한 괜찮습니다.

describe("override properties of local objects", () => {
    it("works and is harmless", () => {
        const myArray = [1];
        myArray.length = 0;
        expect(myArray).toHaveLength(0);
    });
    it("does not affect the next test", () => {
        const myArray = [1];
        expect(myArray).toHaveLength(1);
    });
});

전역 개체에 대해 그렇게 하면 지저분해집니다.

describe("don't override properties of global objects", () => {
    it("works before the property is overridden", () => {
        expect(window.innerWidth).toBeGreaterThan(0);
    });
    it("works, but is evil", () => {
        window.innerWidth = 0;
        expect(window.innerWidth).toBe(0);
    });
    it("fails in the test after the property was overridden", () => {
        expect(() => {
            expect(window.innerWidth).toBeGreaterThan(0); // <-- ERROR: expect(received).toBeGreaterThan(expected)
        }).toThrow(Error);
    });
});

jest.replaceProperty()는 다음을 위해 만들어졌습니다.

describe("use jest.replaceProperty() to override properties of global objects", () => {
    afterEach(() => {
        jest.restoreAllMocks();
    });
    it("works before the property is overridden", () => {
        expect(window.innerWidth).toBeGreaterThan(0);
    });
    it("works and is harmless", () => {
        jest.replaceProperty(window, "innerWidth", 0);
        expect(window.innerWidth).toBe(0);
    });
    it("does not affect the next test", () => {
        expect(window.innerWidth).toBeGreaterThan(0);
    });
});

조롱 방법

메서드는 속성과 유사하게 조롱될 수 있습니다.

describe("override methods of local objects using jest.fn()", () => {
    it("works and is harmless", () => {
        const mySet = new Set([1]);
        mySet.has = jest.fn().mockReturnValue(false);
        expect(mySet.has(1)).toBeFalsy();
    });
    it("does not affect the next test", () => {
        const mySet = new Set([1]);
        expect(mySet.has(1)).toBeTruthy();
    });
});

전역 객체에 myObject.someFunction = jest.fn()을 사용하면 테스트가 서로 의존하고 의미를 잃을 수 있습니다.

describe("don't override methods of global objects using jest.fn()", () => {
    it("works before the method is overridden", () => {
        expect(document.getElementById("foo")).toBeNull();
    });
    it("works, but is evil", () => {
        const el = document.createElement("div");
        document.getElementById = jest.fn().mockReturnValue(el);

        expect(document.getElementById("foo")).toBe(el);
    });
    it("fails in the test after the property was overridden", () => {
        expect(() => {
            expect(document.getElementById("foo")).toBeNull(); // <-- ERROR: expect(received).toBeNull()
        }).toThrow(Error);
    });
});

전역 객체의 메소드를 어떻게 모의해야 합니까? 이것이 jest.spyOn()의 장점입니다:

describe("use jest.spyOn() to override methods of global objects", () => {
    afterEach(() => {
        jest.restoreAllMocks();
    });
    it("works before the method is overridden", () => {
        expect(document.getElementById("foo")).toBeNull();
    });
    it("works and is harmless", () => {
        const el = document.createElement("div");
        jest.spyOn(document, "getElementById").mockReturnValue(el);

        expect(document.getElementById("foo")).toBe(el);
    });
    it("does not affect the next test", () => {
        expect(document.getElementById("foo")).toBeNull();
    });
});

당신은 청소해야합니다

모든 테스트에서 시스템이 동일한(신선하고 깨끗한) 상태인지 확인하려면 각 테스트 후에 모의 상태를 복원해야 합니다.

가장 간단한 해결 방법은 RestoreMocks 구성 속성을 설정하는 것입니다.

가장 간단한 옵션은 afterEach()에서 jest.restoreAllMocks()를 호출하는 것입니다

모든 테스트에 대해 모의하는 방법

때로는 파일의 모든 테스트에 대해 모의 작업을 수행하고 싶을 때가 있습니다. 최상위 레벨 또는 explain() 블록에서 jest.spyOn() 및 jest.replaceProperty()를 사용하는 경우 첫 번째 테스트가 실행된 후 모든 Mock이 재설정됩니다.

최상위 수준에서는 jest.spyOn() 및 jest.replaceProperty() 없이 속성과 메서드를 안전하게 재정의할 수 있습니다.

describe() 블록에 대해서만 모의 작업을 수행하려면 beforeEach() 후크에서 이러한 호출을 수행해야 합니다.

위 내용은 Jest 요약: 전역 객체의 속성과 메서드를 안전하게 모의의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:JS 지도다음 기사:JS 지도