用Jasmine测试JS,有没有办法为类型匹配传入的对象?

时间:2018-10-09 00:39:09

标签: javascript jasmine

如果对象等于期望的模型并匹配其类型,我正在尝试用这两个方法进行测试。

我正在使用茉莉进行测试

我的意思是一个例子(我意识到toMatch是无效的,只是我要寻找的语法的一个例子)

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

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

expect(obj).toMatch(expectedObj)

1 个答案:

答案 0 :(得分:0)

@ david-alsh,我不知道您是否还在寻找答案,但是我知道如何执行此操作的唯一方法是使用Jasmine的自定义匹配器。下面是一个简化的版本(Fiddle here):

// 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)
  })

})