Перебрать объект и проверить свойство существует - Mocha / Chai - PullRequest
0 голосов
/ 10 ноября 2019

Я настраиваю некоторые юнит-тесты в mocha / chai / NodeJs. И я тестирую response, возвращенный в вызове API извлечения.

В моем ответе 9 объектов. И я хочу проверить, что каждый объект содержит свойство с именем " largeImageURL ". Но изо всех сил пытаясь найти лучший способ сделать это.

До сих пор я собирал хак, используя .map для моего объекта, который ищет largeImageURL, возвращает каждое значение. И проверок 9 из них существует.

Это работает и возвращает:

[ { largeImageURL: 'https://pixabay.com/get/55e3d3444a5ab108f5d084609621317b133fd8e04e50744e762c79d2904fc1_1280.jpg' },
  { largeImageURL: 'https://pixabay.com/get/55e3d3474d57b108f5d084609621317b133fd8e04e50744e762c79d2904fc1_1280.jpg' },
  { largeImageURL: 'https://pixabay.com/get/50e6dd454b54b108f5d084609621317b133fd8e04e50744e762c79d2904fc1_1280.jpg' },
  { largeImageURL: 'https://pixabay.com/get/54e6dc4a4f50ac14f6da8c7dda793e781039dee3564c704c722c78d6914ac75c_1280.jpg' },
  { largeImageURL: 'https://pixabay.com/get/57e7d244435aaa14f6da8c7dda793e781039dee3564c704c722c78d6914ac75c_1280.jpg' },
  { largeImageURL: 'https://pixabay.com/get/53e6dc434351b108f5d084609621317b133fd8e04e50744e762c79d2904fc1_1280.jpg' },
  { largeImageURL: 'https://pixabay.com/get/52e0d2444a51b108f5d084609621317b133fd8e04e50744e762c79d2904fc1_1280.jpg' },
  { largeImageURL: 'https://pixabay.com/get/57e8d0404f57ae14f6da8c7dda793e781039dee3564c704c722c78d6914ac75c_1280.jpg' },
  { largeImageURL: 'https://pixabay.com/get/57e8d0434b50a514f6da8c7dda793e781039dee3564c704c722c78d6914ac75c_1280.jpg' } ]

Но я действительно хочу сделать что-то вроде этого:

expect(res.hits).to.have.key(largeImageURL);

Но я не могузаставить мой expect работать таким образом. Возможно ли это?

Вот то, что я написал до сих пор, которое проходит:

describe('1) Check for succcessful fetech API call', () => {
it('a) Should return an object, with an array count of 9 elements', async () => {
    await fetch('https://pixabay.com/api/?key=MY_API_KEY&q=manhattan&image_type=photo&page=1&per_page=9')
        .then((res) => {
            return res.json()
        })
        .then((res) => {
            console.log(res.hits);
            expect(res).to.be.an('object');
            expect(res.hits).to.have.lengthOf(9);

            const imageURLs = res.hits.map(x => ({largeImageURL: x.largeImageURL}));
            expect(imageURLs).to.have.lengthOf(9);
        })
})

})

Console.log производит это, кстати. Любые идеи будут высоко оценены!

  1) Check for succcessful fetech API call
[ { largeImageURL: 'https://pixabay.com/get/55e3d3444a5ab108f5d084609621317b133fd8e04e50744e762c79d2904fc1_1280.jpg',
    webformatHeight: 360,
    webformatWidth: 640,
    likes: 646,
    imageWidth: 2560,
    id: 336708,
    user_id: 242387,
    views: 302373,
    comments: 141,
    pageURL: 'https://pixabay.com/photos/manhattan-empire-state-building-336708/',
    imageHeight: 1440,
    webformatURL: 'https://pixabay.com/get/55e3d3444a5ab108f5d084609621317b133fd8e04e50744e762c79d2904fc1_640.jpg',
    type: 'photo',
    previewHeight: 84,
    tags: 'manhattan, empire state building, new york city',
    downloads: 141972,
    user: 'Free-Photos',
    favorites: 775,
    imageSize: 1587009,
    previewWidth: 150,
    userImageURL: 'https://cdn.pixabay.com/user/2014/05/07/00-10-34-2_250x250.jpg',
    previewURL: 'https://cdn.pixabay.com/photo/2014/05/03/01/04/manhattan-336708_150.jpg' },
  { largeImageURL: 'https://pixabay.com/get/55e3d3474d57b108f5d084609621317b133fd8e04e50744e762c79d2904fc1_1280.jpg',
    webformatHeight: 426,
    webformatWidth: 640,
    likes: 775,
    imageWidth: 3000,
    id: 336475,
    user_id: 242387,
    views: 266538,
    comments: 110,
    pageURL: 'https://pixabay.com/photos/new-york-city-brooklyn-bridge-night-336475/',
    imageHeight: 2000,
    webformatURL: 'https://pixabay.com/get/55e3d3474d57b108f5d084609621317b133fd8e04e50744e762c79d2904fc1_640.jpg',
    type: 'photo',
    previewHeight: 99,
    tags: 'new york city, brooklyn bridge, night',
    downloads: 110902,
    user: 'Free-Photos',
    favorites: 724,
    imageSize: 1230835,
    previewWidth: 150,
    userImageURL: 'https://cdn.pixabay.com/user/2014/05/07/00-10-34-2_250x250.jpg',
    previewURL: 'https://cdn.pixabay.com/photo/2014/05/02/23/46/new-york-city-336475_150.jpg' },
  { largeImageURL: 'https://pixabay.com/get/50e6dd454b54b108f5d084609621317b133fd8e04e50744e762c79d2904fc1_1280.jpg',
    webformatHeight: 426,
    webformatWidth: 640,
    likes: 443,
    imageWidth: 5184,
    id: 668616,
    user_id: 777390,
    views: 241940,
    comments: 72,
    pageURL: 'https://pixabay.com/photos/new-york-skyline-new-york-city-city-668616/',
    imageHeight: 3456,
    webformatURL: 'https://pixabay.com/get/50e6dd454b54b108f5d084609621317b133fd8e04e50744e762c79d2904fc1_640.jpg',
    type: 'photo',
    previewHeight: 99,
    tags: 'new york, skyline, new york city',
    downloads: 84616,
    user: 'mpewny',
    favorites: 439,
    imageSize: 8661087,
    previewWidth: 150,
    userImageURL: 'https://cdn.pixabay.com/user/2018/02/04/18-35-12-410_250x250.jpg',
    previewURL: 'https://cdn.pixabay.com/photo/2015/03/11/12/31/new-york-668616_150.jpg' },
  { largeImageURL: 'https://pixabay.com/get/54e6dc4a4f50ac14f6da8c7dda793e781039dee3564c704c722c78d6914ac75c_1280.jpg',
    webformatHeight: 426,
    webformatWidth: 640,
    likes: 351,
    imageWidth: 8256,
    id: 2699520,
    user_id: 4591426,
    views: 109012,
    comments: 35,
    pageURL: 'https://pixabay.com/photos/new-york-cityscape-night-city-2699520/',
    imageHeight: 5504,
    webformatURL: 'https://pixabay.com/get/54e6dc4a4f50ac14f6da8c7dda793e781039dee3564c704c722c78d6914ac75c_640.jpg',
    type: 'photo',
    previewHeight: 99,
    tags: 'new york, cityscape, night',
    downloads: 54675,
    user: 'igormattio',
    favorites: 332,
    imageSize: 11053173,
    previewWidth: 150,
    userImageURL: '',
    previewURL: 'https://cdn.pixabay.com/photo/2017/08/31/05/36/new-york-2699520_150.jpg' },
  { largeImageURL: 'https://pixabay.com/get/57e7d244435aaa14f6da8c7dda793e781039dee3564c704c722c78d6914ac75c_1280.jpg',
    webformatHeight: 426,
    webformatWidth: 640,
    likes: 316,
    imageWidth: 4867,
    id: 1777986,
    user_id: 3628174,
    views: 80039,
    comments: 34,
    pageURL: 'https://pixabay.com/photos/usa-manhattan-contrasts-new-york-1777986/',
    imageHeight: 3246,
    webformatURL: 'https://pixabay.com/get/57e7d244435aaa14f6da8c7dda793e781039dee3564c704c722c78d6914ac75c_640.jpg',
    type: 'photo',
    previewHeight: 99,
    tags: 'usa, manhattan, contrasts',
    downloads: 42274,
    user: 'wiggijo',
    favorites: 384,
    imageSize: 5819085,
    previewWidth: 150,
    userImageURL: 'https://cdn.pixabay.com/user/2016/10/28/09-04-12-659_250x250.jpeg',
    previewURL: 'https://cdn.pixabay.com/photo/2016/10/28/13/09/usa-1777986_150.jpg' },
  { largeImageURL: 'https://pixabay.com/get/53e6dc434351b108f5d084609621317b133fd8e04e50744e762c79d2904fc1_1280.jpg',
    webformatHeight: 640,
    webformatWidth: 640,
    likes: 255,
    imageWidth: 2048,
    id: 569093,
    user_id: 364018,
    views: 98250,
    comments: 28,
    pageURL: 'https://pixabay.com/photos/city-manhattan-sunset-town-569093/',
    imageHeight: 2048,
    webformatURL: 'https://pixabay.com/get/53e6dc434351b108f5d084609621317b133fd8e04e50744e762c79d2904fc1_640.jpg',
    type: 'photo',
    previewHeight: 150,
    tags: 'city, manhattan, sunset',
    downloads: 55895,
    user: 'Life-Of-Pix',
    favorites: 370,
    imageSize: 698912,
    previewWidth: 150,
    userImageURL: 'https://cdn.pixabay.com/user/2014/08/21/23-01-42-554_250x250.jpg',
    previewURL: 'https://cdn.pixabay.com/photo/2014/12/15/13/57/city-569093_150.jpg' },
  { largeImageURL: 'https://pixabay.com/get/52e0d2444a51b108f5d084609621317b133fd8e04e50744e762c79d2904fc1_1280.jpg',
    webformatHeight: 301,
    webformatWidth: 640,
    likes: 263,
    imageWidth: 5183,
    id: 407703,
    user_id: 242387,
    views: 100552,
    comments: 64,
    pageURL: 'https://pixabay.com/photos/manhattan-new-york-city-407703/',
    imageHeight: 2444,
    webformatURL: 'https://pixabay.com/get/52e0d2444a51b108f5d084609621317b133fd8e04e50744e762c79d2904fc1_640.jpg',
    type: 'photo',
    previewHeight: 70,
    tags: 'manhattan, new york city, empire state building',
    downloads: 55127,
    user: 'Free-Photos',
    favorites: 375,
    imageSize: 3543546,
    previewWidth: 150,
    userImageURL: 'https://cdn.pixabay.com/user/2014/05/07/00-10-34-2_250x250.jpg',
    previewURL: 'https://cdn.pixabay.com/photo/2014/08/01/15/51/manhattan-407703_150.jpg' },
  { largeImageURL: 'https://pixabay.com/get/57e8d0404f57ae14f6da8c7dda793e781039dee3564c704c722c78d6914ac75c_1280.jpg',
    webformatHeight: 425,
    webformatWidth: 640,
    likes: 204,
    imageWidth: 4201,
    id: 1853552,
    user_id: 2286921,
    views: 64835,
    comments: 8,
    pageURL: 'https://pixabay.com/photos/architecture-new-york-city-manhattan-1853552/',
    imageHeight: 2790,
    webformatURL: 'https://pixabay.com/get/57e8d0404f57ae14f6da8c7dda793e781039dee3564c704c722c78d6914ac75c_640.jpg',
    type: 'photo',
    previewHeight: 99,
    tags: 'architecture, new york city, manhattan',
    downloads: 36684,
    user: 'Pexels',
    favorites: 279,
    imageSize: 3935888,
    previewWidth: 150,
    userImageURL: 'https://cdn.pixabay.com/user/2016/03/26/22-06-36-459_250x250.jpg',
    previewURL: 'https://cdn.pixabay.com/photo/2016/11/23/15/32/architecture-1853552_150.jpg' },
  { largeImageURL: 'https://pixabay.com/get/57e8d0434b50a514f6da8c7dda793e781039dee3564c704c722c78d6914ac75c_1280.jpg',
    webformatHeight: 360,
    webformatWidth: 640,
    likes: 145,
    imageWidth: 5000,
    id: 1850129,
    user_id: 2286921,
    views: 59983,
    comments: 7,
    pageURL: 'https://pixabay.com/photos/architecture-new-york-city-manhattan-1850129/',
    imageHeight: 2813,
    webformatURL: 'https://pixabay.com/get/57e8d0434b50a514f6da8c7dda793e781039dee3564c704c722c78d6914ac75c_640.jpg',
    type: 'photo',
    previewHeight: 84,
    tags: 'architecture, new york city, manhattan',
    downloads: 34065,
    user: 'Pexels',
    favorites: 258,
    imageSize: 3275708,
    previewWidth: 150,
    userImageURL: 'https://cdn.pixabay.com/user/2016/03/26/22-06-36-459_250x250.jpg',
    previewURL: 'https://cdn.pixabay.com/photo/2016/11/22/19/17/architecture-1850129_150.jpg' } ]
    ✓ a) Should return an object, with an array count of 9 elements (196ms)

1 Ответ

0 голосов
/ 13 ноября 2019

Вы можете использовать плагин chai-each

Увидимся во фрагменте ниже, где я включил chaiEach как функцию для целей браузера

chai.use(chaiEach);
expect = chai.expect;
test = function(testName, expected) {
  try {
    expect(expected).each.have.property('foo');
    console.log(testName + " has sucsess");
  } catch(e) {
   console.log(testName + " fails with : " + e);
  }
};

test("Nominal case", [{foo:'bar'},{foo:'buzz'}]);
test("Error case", [{foo:'bar'}, {bar:0},{foo:'buzz'}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.2.0/chai.min.js"></script>
<script>chaiEach = function(chai, utils) {

  const propertyNames = Object.getOwnPropertyNames(chai.Assertion.prototype);

  const propertyDescs = {};
  for (const name of propertyNames) {
    propertyDescs[name] = Object.getOwnPropertyDescriptor(chai.Assertion.prototype, name);
  }

  const methodNames = propertyNames.filter(name => {
    return name !== "assert" && typeof propertyDescs[name].value === "function";
  });

  chai.Assertion.addProperty('each', function () {
    const each = utils.flag(this, 'each') || 0;
    utils.flag(this, 'each', each + 1);
  });

  methodNames.forEach(methodName => {
    chai.Assertion.overwriteMethod(methodName, function (_super) {
      return function assertEach () {
        if (utils.flag(this, 'each')) {
          const each = utils.flag(this, 'each');
          utils.flag(this, 'each', each - 1);
          var obj = this._obj;

          new chai.Assertion(obj).is.an.instanceOf(Array);
          obj.map(item => {
            const that = cloneAssertion(this);
            utils.flag(that, 'object', item);
            _super.apply(that, arguments);
            return utils.flag(that, 'object');
          });
      } else {
        _super.apply(this, arguments);
      }
    };
    });
  });

  function cloneAssertion(original) {
    const copy = Object.create(original);
    utils.transferFlags(original, copy, false);

    return copy;
  }
};</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...