-1

I have a homework assignment which tasks one to begin to write simple tests.

They use this as an example.

Write an assertEqual function from scratch.

It should compare actual and expected values with strict equality (not typecasting).

SUCCESS CASE

function multiplyByTwo(n) {
  return n * 2; 
} 
var output = multiplyByTwo(2); 
// returns 4 assertEqual(output, 4, 'it doubles 2 to 4'); 
// console output: // passed

FAILURE CASE

function multiplyByTwo(n) {
  return (n * 2) + 1; // an incorrect implementation
}
var output = multiplyByTwo(2); // returns 5
assertEqual(output, 4, 'it doubles 2 to 4');
// console output:
// FAILED [it doubles 2 to 4] Expected "4", but got "5"

This is what I have so far...

function compareWithStrictEquality(val1, val2) {
  return val1 === val2;
}

function assertEqual(actual, expected, testName) {
  testName = assertEqual.name + ' : should compare actual and expected values with strict equality (not typecasting).';
  console.log(testName);

 return (actual()) === typeof 'boolean';

}

I didn't go to far because I don't know where to begin! Also—I have worked with some JavaScript assesments in the past. Looking at the example made me think I had to write some kind of complex logic analogous to the test suite I linked to...How else would it figure out if your function was doing?

Somehow I believe it is far simpler and I am overthinking it!

Thanks in advance!

Antonio Pavicevac-Ortiz
  • 7,239
  • 17
  • 68
  • 141

1 Answers1

1

Assuming you don't have to do deep object inspection (more on that later), it looks like you're on the right path and nearly done actually.

In your assertEqual you have to do the comparison and return the message. A simple way to do this:

var passed = compareWithStrictEquality(actual, expected)
if (passed) console.log('passed')
else console.log('FAILED ' + testName + ' Expected ' + expected + ', but got ' + actual)

Note this is not going to work if you need to compare objects. For example:

{} === {}
// output: false

If you need to do object comparison you'll need some form of deep comparison: Object comparison in JavaScript

Community
  • 1
  • 1
shotor
  • 763
  • 6
  • 17