How to match Jasmine's 'toHavenBeenCalledWith()' with a multiline literal string

360 Views Asked by At

I have a method that takes a script written in a multiline literal String, and which I call in several other methods. It looks something like:

myMethod(`
        thisIsMyScript();
        itDoesThings();
    `);

To test it has been called with the expected script I'm doing:

  it('should call script', async function () {
    const scriptMock = `
            thisIsMyScript();
            itDoesThings();
`;
    spyOn(component, 'myMethod');

    await component.testedMethod();
    
    expect(component.myMethod).toHaveBeenCalledWith(
      scriptMock
    );
});

But then my test is failing because both strings don't match:

   Expected spy myMethod to have been called with:
     [ '
            thisIsMyScript();
            itDoesThings();
   ' ]
   but actual call was:
     [ '
            thisIsMyScript();
            itDoesThings();
           ' ].

How should I handle those situations?

EDIT: Following AliF50's solution, here are the tweaks I had to made (pasting here instead of in comment for a better code formatting)In case anyone needs

const arg = myMethodSpy.calls.mostRecent().args[0].toString();   
// it won't recognize this as a string else.
expect(arg.replace(/ +/g, '')).toBe(scriptMock.replace(/ +/g, ''));  
// it was giving me problems with the inner spaces else
1

There are 1 best solutions below

1
AliF50 On BEST ANSWER

I would get a handle on the argument and assert that it contains the strings.

Something like this:

  it('should call script', async function () {
    const scriptMock = `
            thisIsMyScript();
            itDoesThings();
`;
    const myMethodSpy = spyOn(component, 'myMethod');

    await component.testedMethod();
    
    // we can get the arguments as an array
    // since there is only one argument, it will be the 0th one in the array
    const arg = myMethodSpy.calls.mostRecent().args[0];
    expect(arg.includes('thisIsMyScript();')).toBeTrue();
    expect(arg.includes('itDoesThings();')).toBeTrue();
    // this might work too if we trim both strings
    expect(arg.trim()).toBe(scriptMock.trim());
});