programing

Jest.js 오류: "수신됨: 동일한 문자열로 직렬화"

codeshow 2023. 10. 4. 23:04
반응형

Jest.js 오류: "수신됨: 동일한 문자열로 직렬화"

이 테스트에 이상한 문제가 생겼습니다.

deal.test.js

import Deal from "../src/models/Deal";
import apiProducts from "../__mocks__/api/products";

describe("Deal", () => {
  describe("Deal.fromApi", () => {
    it("takes an api product and returns a Deal", () => {
      const apiDeal = apiProducts[0];
      const newDeal = Deal.fromApi(apiDeal);
      const expected = expectedDeal();
      expect(newDeal).toEqual(expected);
    });
  });
});

딜.js

export default class Deal {
  // no constructor since we only ever create a deal from Deal.fromApi

  static fromApi(obj: Object): Deal {
    const deal = new Deal();
    deal.id = obj.id;
    deal.name = obj.name;
    deal.slug = obj.slug;
    deal.permalink = obj.permalink;
    deal.dateCreated = obj.date_created;
    deal.dateModified = obj.date_modified;
    deal.status = obj.status;
    deal.featured = obj.featured;
    deal.catalogVisibility = obj.catalog_visibility;
    deal.descriptionHTML = obj.description;
    deal.shortDescriptionHTML = obj.short_description;
    deal.price = Number(obj.price);
    deal.regularPrice = Number(obj.regular_price);
    deal.salePrice = Number(obj.sale_price);
    deal.dateOnSaleFrom = obj.date_on_sale_from;
    deal.dateOnSaleTo = obj.date_on_sale_to;
    deal.onSale = obj.on_sale;
    deal.purchasable = obj.purchasable;
    deal.relatedIds = obj.related_ids;
    deal.upsellIds = obj.upsell_ids;
    deal.crossSellIds = obj.cross_sell_ids;
    deal.categories = obj.categories;
    deal.tags = obj.tags;
    deal.images = obj.images;
    return deal;
  }

 descriptionWithTextSize(size: number): string {
    return this.descriptionWithStyle(`font-size:${size}`);
  }

  descriptionWithStyle(style: string): string {
    return `<div style="${style}">${this.description}</div>`;
  }

  distanceFromLocation = (
    location: Location,
    unit: unitOfDistance = "mi"
  ): number => {
    return distanceBetween(this.location, location);
  };

  distanceFrom = (otherDeal: Deal, unit: unitOfDistance = "mi"): number => {
    return distanceBetween(this.location, otherDeal.location);
  };

  static toApi(deal: Deal): Object {
    return { ...deal };
  }
}

테스트가 실패하고 다음 오류가 발생합니다.

  ● Deal › Deal.fromApi › takes an api product and returns a Deal

    expect(received).toEqual(expected) // deep equality

    Expected: {"catalogVisibility": "visible", "categories": [{"id": 15, "name": "New York", "slug": "new-york"}], "crossSellIds": [34, 31], "dateCreated": "2019-05-18T17:36:14", "dateModified": "2019-05-18T17:39:02", "dateOnSaleFrom": null, "dateOnSaleTo": null, "descriptionHTML": "<p>Pete's Tavern<br />
    129 E 18th St<br />
    New York, NY 10003</p>
    <p>Weekdays from 4 p.m. to 7 p.m.<br />
    $5 wines and beers</p>
    ", "distanceFromLocation": [Function anonymous], "featured": false, "id": 566, "images": [{"alt": "", "date_created": "2019-05-18T17:38:52", "date_created_gmt": "2019-05-18T17:38:52", "date_modified": "2019-05-18T17:38:52", "date_modified_gmt": "2019-05-18T17:38:52", "id": 567, "name": "wine and beers2", "src": "https://tragodeals.com/wp-content/uploads/2019/05/wine-and-beers2.jpg"}], "name": "Wines and beers", "onSale": true, "permalink": "https://tragodeals.com/product/wines-and-beers/", "price": 5, "purchasable": true, "regularPrice": 11, "relatedIds": [552, 564, 390, 37, 543], "salePrice": 5, "shortDescriptionHTML": "<p>$5 wines and beers</p>
    ", "slug": "wines-and-beers", "status": "publish", "tags": [{"id": 58, "name": "beers", "slug": "beers"}, {"id": 54, "name": "Cocktails", "slug": "cocktails"}, {"id": 45, "name": "drink", "slug": "drink"}, {"id": 57, "name": "wine", "slug": "wine"}], "upsellIds": [53]}
    Received: serializes to the same string

    > 15 |       expect(newDeal).toEqual(expected);
         |                       ^
      16 |     });
      17 |   });
      18 | });

      at Object.toEqual (__tests__/deal.test.js:15:23)

조사하기 위해 이 루프를 삽입했습니다.

for (let key in expected) {
  expect(expected[key]).toEqual(newDeal[key]);
}

그리고 문제가 기능에 있다는 것을 알았습니다.그래서 저는 전체 테스트를 이렇게 바꿨습니다.

      for (let key in expected) {
        if (typeof expected[key] === "function") continue;
        expect(expected[key]).toEqual(newDeal[key]);
      }
     // expect(newDeal).toEqual(expected);

통과하고, 통과해야 할 때도 실패합니다., 내가 (이 질문의 이전 버전을 읽었을 때 제가 이해하지 못했던 합격 테스트를 받았기 때문입니다)였기 때문입니다.return가 을 때 고리에서 온 입니다.continue(

는 표준 주장 할수 좋겠습니다.expect(newDeal).toEqual(expected)를 확인하는 것에 않는 것 ()Deal 함수와 같음.

를. PS를 하는 것이 .toMatchObject 하지만 슬프게도:

  ● Deal › Deal.fromApi › takes an api product and returns a Deal

    expect(received).toMatchObject(expected)

    - Expected
    + Received

    @@ -1,6 +1,6 @@
    - Deal {
    + Object {
        "address": "129 E 18th St New York, NY 10003",
        "catalogVisibility": "visible",
        "categories": Array [
          Object {
            "id": 15,

      13 |         expect(expected[key]).toEqual(newDeal[key]);
      14 |       }
    > 15 |       expect(newDeal).toMatchObject(expected);
         |                       ^
      16 |     });
      17 |   });
      18 | });

다른 동료들과 마찬가지로 배열 비교와 관련하여 이 문제가 발생했습니다. 기본적으로 배열에서 가장 큰 문자열을 얻는 함수를 테스트하고 있었습니다. 추가적으로 해당 문자열 중 1개 이상이 가능한 가장 큰 길이와 일치하면 배열을 반환해야 합니다.

테스트를 시작하자 다음과 같은 메시지가 나타납니다.

screenshot of jest results

그래서 제가 교체를 했습니다.toBe

expect(function(array1)).toBe('one result')

와 함께toStrictEqual

expect(function(array2)).toStrictEqual(['more than one', 'more than one']);

있는 가 base64 로를 의 직렬화를 를 진행했습니다. 객체의 직렬화를 비교하기 위해 테스트를 관리했습니다.JSON.stringify:

expect(JSON.stringify(newDeal)).toMatchObject(JSON.stringify(expected));

한 배열에 인덱스가 -1로 설정된 요소가 있는 배열을 비교하려고 할 때 이 문제가 발생했습니다(0에서 N까지의 숫자를 제외하고 설정할 다른 키를 상상해 보십시오).따라서 다음 시나리오에서 이 오류가 발생할 수 있습니다.

const arr = [1, 2]
arr[-1] = 'foo'
expect(arr).toEqual([1, 2])

둘 다 같은 문자열로 직렬화했지만 동일하지 않습니다.

한 어레이가 Graphql의 레졸버에서 돌아오는 어레이와 다른 어레이가 테스트 입력에서 돌아오는 어레이를 비교하려고 할 때 이 문제가 발생했습니다.
에 Graphql했습니다가 것을 했습니다.__proto____proto__: Object구조물 이외의 유형을 검사하기 때문StrictEqual에 실패하게 됩니다.그래서 제 경우에는 유형이 실패로 이어졌습니다.로 변경하기toEqual문제를 해결했습니다.

                expect(res.data.myMutation.values).toEqual(
                    testInput.values,
                );

내 상황에서 나는 프록시 객체 대 일반 객체를 확인하는 것은 매우 동등했습니다.

const proxyObject = new Proxy({}, {
    get: function(target, prop) {
        return Object.hasOwnProperty.call(target, prop) ? target[prop] : '';
    }
})
expect(proxyObject).toEqual({})
// Expected: {}
// Received: serializes to the same string

다음이 되어야 합니다.

expect(proxyObject).toMatchObject({})

MongoDb ObjectId 두 개를 비교하는 과정에서 비슷한 문제가 있었습니다.그 문제를 극복하기 위해서 저는

expect(`${thisObject._id}`).toEqual(`${thatObject._id}`);

저는 농담에 대해서도 같은 문제가 있었습니다.제 경우에는 객체 배열(기본적으로 모델 클래스)을 비교했습니다.그리고 그 수업에서 나는 함수를 화살표 함수로 정의했습니다.

문제는 비교하면서 화살표 기능도 확인한다는 것입니다.그리고 화살표 함수는 클래스 전체에 하나의 인스턴스만 있는 일반 함수와 달리 모든 개체에 대해 다른 인스턴스를 생성하므로 화살표 함수 비교 결과가 거짓이 됩니다.

따라서 간단한 해결책은 수업시간에 화살표 함수를 정상 함수로 변환하는 것입니다.

용도:

class ClassName {
  yourFunc(){
    // your code here
  }
};

대신:

class ClassName {
  yourFunc = () => {
    // your code here
  };
};

그래서 일단 정상적인 기능으로 전환하면 간단히 사용할 수 있습니다.toEqual()비교를 위하여

정상적인 기능으로 전환할 수 없는 경우 사용할 수 있습니다.JSON.stringify()그것들을 먼저 문자열로 변환하고 나서 사용합니다.toEqual()아니면toBe().

언급URL : https://stackoverflow.com/questions/56839801/jest-js-error-received-serializes-to-the-same-string

반응형