Merge branch 'stephanreiter-better-toHaveSize'

* Merges #2033 from @stephanreiter
This commit is contained in:
Steve Gravrock
2024-07-13 14:01:32 -07:00
3 changed files with 53 additions and 8 deletions

View File

@@ -6558,7 +6558,7 @@ getJasmineRequireObj().toHaveSize = function(j$) {
* array = [1,2];
* expect(array).toHaveSize(2);
*/
function toHaveSize() {
function toHaveSize(matchersUtil) {
return {
compare: function(actual, expected) {
const result = {
@@ -6573,12 +6573,29 @@ getJasmineRequireObj().toHaveSize = function(j$) {
throw new Error('Cannot get size of ' + actual + '.');
}
let actualSize;
if (j$.isSet(actual) || j$.isMap(actual)) {
result.pass = actual.size === expected;
actualSize = actual.size;
} else if (isLength(actual.length)) {
result.pass = actual.length === expected;
actualSize = actual.length;
} else {
result.pass = Object.keys(actual).length === expected;
actualSize = Object.keys(actual).length;
}
result.pass = actualSize === expected;
if (!result.pass) {
result.message = function() {
return (
'Expected ' +
matchersUtil.pp(actual) +
' with size ' +
actualSize +
' to have size ' +
expected +
'.'
);
};
}
return result;

View File

@@ -15,6 +15,17 @@ describe('toHaveSize', function() {
expect(result.pass).toBe(false);
});
it('informs about the size of an array whose length does not match', function() {
const matcher = jasmineUnderTest.matchers.toHaveSize({
pp: jasmineUnderTest.makePrettyPrinter()
}),
result = matcher.compare([1, 2, 3], 2);
expect(result.message()).toEqual(
'Expected [ 1, 2, 3 ] with size 3 to have size 2.'
);
});
it('passes for an object with the proper number of keys', function() {
const matcher = jasmineUnderTest.matchers.toHaveSize(),
result = matcher.compare({ a: 1, b: 2 }, 2);

View File

@@ -9,7 +9,7 @@ getJasmineRequireObj().toHaveSize = function(j$) {
* array = [1,2];
* expect(array).toHaveSize(2);
*/
function toHaveSize() {
function toHaveSize(matchersUtil) {
return {
compare: function(actual, expected) {
const result = {
@@ -24,12 +24,29 @@ getJasmineRequireObj().toHaveSize = function(j$) {
throw new Error('Cannot get size of ' + actual + '.');
}
let actualSize;
if (j$.isSet(actual) || j$.isMap(actual)) {
result.pass = actual.size === expected;
actualSize = actual.size;
} else if (isLength(actual.length)) {
result.pass = actual.length === expected;
actualSize = actual.length;
} else {
result.pass = Object.keys(actual).length === expected;
actualSize = Object.keys(actual).length;
}
result.pass = actualSize === expected;
if (!result.pass) {
result.message = function() {
return (
'Expected ' +
matchersUtil.pp(actual) +
' with size ' +
actualSize +
' to have size ' +
expected +
'.'
);
};
}
return result;