javascriptjestjs

Jest Expected true to be false: writing a test to check template string usage


I have the following solution:

function doubleMessage(number) {
  return `Your number doubled is ${2 * number}`;
}

I need a describe block with Jest to check that the above code block is using template strings. I wrote a helper function outside the describe block to be able to create an expectation like so:

const result = doubleMessage(5);
expect(checkTemplateStringUsage(result)).toBe(true);

I get Expected true to be false as an error.


Solution

  • @jonrsharpe was absolutely correct, for such a test, you don't test implementation of template strings because you cannot, instead you test behavior. I guess I got hung up on trying to test the use of the template strings because that is what my custom quiz is supposed to ask the user to do, implement template strings correctly. Thanks everyone.

    describe('doubleMessage function', () => {
      it('should return the correct message with the doubled number', () => {
        // Function definition
        function doubleMessage(number) {
          return `Your number doubled is ${2 * number}`;
        }
    
        // Test the function with different inputs
        const input = 5;
        const expectedOutput = 'Your number doubled is 10';
        const result = doubleMessage(input);
    
        // Check if the result matches the expected output
        expect(result).toBe(expectedOutput);
      });
    });