source

Jest: 객체 키와 값을 테스트하는 방법

goodcode 2023. 1. 9. 21:45
반응형

Jest: 객체 키와 값을 테스트하는 방법

나는 가지고 있다mapModule컴포넌트를 Import하여 내보냅니다.

import ComponentName from '../components/ComponentName';

export default {
  name: ComponentName,
};

어떻게 하면 테스트 할 수 있을까요?mapModule올바른 내보내기 키와 값이 있으며 늘 또는 정의되어 있지 않은지 여부를 확인합니다.

농담 버전 23.3.0에서는

expect(string).toMatch(string) 

는 문자열을 요구합니다.

용도:

const expected = { name:'component name' }
const actual = { name: 'component name', type: 'form' }
expect(actual).toMatchObject(expected)

결과는 시험에 합격하고 있다.

다음 중 하나를 사용할 수 있습니다.

toEqual 및 toMatchObject는 오브젝트의 템플릿매처입니다

let Obj = {name: 'component name', id: 2};
expect(oneObj).toEqual({name: 'component name'}) // false, should be exactly equal all Obj keys and values  
expect(oneObj).toMatchObject({name: 'component name'}) // true

또는 Have Property를 쉽게 사용할 수 있습니다.

let Obj = {name: 'component name'};
expect(oneObj).toHaveProperty('name') // true
expect(oneObj).toHaveProperty('name', 'component name') // true

체크하는 것에 주의해 주세요.

"JavaScript 객체가 객체의 속성 서브셋과 일치합니다."

그래서 다음과 같은 의도하지 않은 어설션이 있을있습니다.

expect({ a: 1, b: 2 }).toMatchObject({ a: 1 }); // pass

오브젝트를 정확하게 일치시키는 경우 다음부터 사용할 수 있는를 사용해야 합니다.

expect({ a: 1, b: 2 }).toStrictEqual({ a: 1 }); // fail

이 힌트를 덧붙이자면, 특히 조롱된 서비스에 대한 논거와 일치할 때, 제 자신의 테스트에 보다 세밀한 정보를 제공한다고 생각했습니다.

expect.objectContaining({
   url: expect.stringContaining('https://'),
})

또는 regex를 사용하여expect.stringMatching지정된 정규식을 값과 비교하여 테스트합니다.꽤 깔끔하네요.

expect.string 포함 expect.string 매칭

하나의 키에 대해 체크아웃할 수 있습니다.

expect(Boolean(obj[prop])).toBe(true | false);

복수의 키(모두 존재해야 함)의 경우는, 다음과 같이 사용할 수 있습니다.

expect(Boolean(obj[prop1]) && Boolean(obj[prop2])).toBe(true | false);

여러 키(하나가 있어야 하는 경우)의 경우

expect(Boolean(obj[prop1]) || Boolean(obj[prop2])).toBe(true | false);

또 다른 방법은 다음과 같습니다.

expect(JSON.stringify(object)).toBe(JSON.stringify(object))

이렇게 하면 개체가 동일한지 확인할 수 있습니다.

단, 이것을 사용하면:

expect(object).toMatchObject(object)

대부분의 경우 가장 좋은 옵션입니다.

언급URL : https://stackoverflow.com/questions/47754777/jest-how-to-test-for-object-keys-and-values

반응형