gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 00:58:33 24 4
gpt4 key购买 nike

我正在尝试用这个测试两件事,如果一个对象等于预期模型,并匹配它的类型。

我正在使用 Jasmine 进行测试

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

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

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

expect(obj).toMatch(expectedObj)

最佳答案

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

})

关于javascript - 用 Jasmine 测试 JS,有没有办法匹配传入对象的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52711799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com