[Vuejs]-Jest: how to test console.log haveBeenCalled with a subset of expected value?

1๐Ÿ‘

โœ…

i found a solution for this situations, based on jest https://jestjs.io/docs/en/expect#expectstringcontainingstring:

expect.stringContaining(string)

expect.stringContaining(string) matches the received value if it is a string that contains the exact expected string.

expect.stringMatching(string | regexp)

expect.stringMatching(string | regexp) matches the received value if it is a string that matches the expected string or regular expression.

expect(console.log).toHaveBeenCalledWith(expect.stringMatching(/--->total execution time:0.*/));

or

const total_time ='--->total execution time:0.';
expect(console.log).toHaveBeenCalledWith(expect.stringContaining(total_time));

update:
for the sake of completeness which other developer may have similar problem in testing error section. we can throw error, just consider that you should use try catch to send the error thrown to the right part:

  it("should throw error with fn.name and it's calculated time", function () {
    const errorThrown = util_addTimeLogger(() => {
      throw new TypeError();
    });
    const error_msg = "exception thrown : threw TypeError--->time:";
    try {
      errorThrown();
    }
    catch (error) {
      expect(console.log).toHaveBeenCalledWith("entering : []");
      expect(console.log).toHaveBeenCalledWith(expect.stringContaining(error_msg));
    }
  });
๐Ÿ‘คSeyyedKhandon

Leave a comment