Тестируя JS с Jasmine, есть ли способ сопоставить входящий объект для типов? - PullRequest
0 голосов
/ 09 октября 2018

Я пытаюсь проверить две вещи с этим, если объект равен ожидаемой модели, и сопоставить типы на нем.

Я использую Жасмин для тестирования

Примеря имею в виду (я понимаю, что toMatch недействительно, просто пример синтаксиса, который я ищу)

const obj = {
    one: 'a value',
    two: 99
}

const expectedObj = {
    one: 'string',
    two: 'number'
}

expect(obj).toMatch(expectedObj)

1 Ответ

0 голосов
/ 21 октября 2018

@ david-alsh, я не знаю, ищите ли вы ответ на этот вопрос, но единственный способ, которым я знаю, как это сделать, - использовать пользовательские совпадения Жасмин.Ниже приведена упрощенная версия ( Fiddle здесь ):

// Utility function to Create an object with the passed object properties as keys, 
// but the value for each key being the type from the original object.  Used
// for comparing two object's property types  
getPropertyTypes = obj => {
    let keys = Object.keys(obj);
  return keys.reduce( (typeObj, key) => {
    typeObj[key] = typeof obj[key];
    return typeObj;
  }, {})
}

// Define Jasmine's Custom Matcher.  For this match to be true, the 
// actual and expected object must have the same properties of the same type
var customMatchers = {
    toHaveSameProperties: function(util, customEqualityTesters) {
  return {
      compare: function(actual, expected) {
                if (expected === undefined) {
            expected = {};
        }
        let result = {};

        let actualPropertyTypes = getPropertyTypes(actual);
        let expectedPropertyTypes = getPropertyTypes(expected);

        result.pass = util.equals(actualPropertyTypes, expectedPropertyTypes,
            customEqualityTesters);

        if (result.pass) {
            result.message = `Expected ${actual} not to have the same \
          property types as  ${expected}, but it did`;
        } else {
            result.message = `Expected ${actual} and ${expected} to have \
          the same property types, but it did not`
        }
        return result
      }
    }
  }
}

const obj = {
    one: 'a value',
    two: 99
}

const expectedObj = {
    one: 'string',
    two: 999
}
const expectedObjReverse = {
    two: 666,
    one: 'number'
}
const expectedObjDifferentProperties = {
    one: 'string',
    three: 666
}
const expectedObjDifferentPropertyTypes = {
    one: 'string',
    two: 'number'
}


/*** SPECS ***/
describe('Custom matcher', function() {

    beforeEach(function() {
    jasmine.addMatchers(customMatchers);
  })

  it('should match objects with same properties', function() {
    expect(obj).toHaveSameProperties(expectedObj);
    expect(obj).toHaveSameProperties(expectedObjReverse);
  })
  it('should not match objects if properties are different', function() {
    expect(obj).not.toHaveSameProperties(expectedObjDifferentProperties)
  })
  it('should not match objects if properties types are different', function() {
    expect(obj).not.toHaveSameProperties(expectedObjDifferentPropertyTypes)
  })

})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...