首页 > 解决方案 > 如何将 Jasmine 的“toHavenBeenCalledWith()”与多行文字字符串匹配

问题描述

我有一个方法,它接受一个用多行文字字符串编写的脚本,我在其他几个方法中调用它。它看起来像:

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

为了测试它已经用我正在做的预期脚本调用:

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

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

但是后来我的测试失败了,因为两个字符串都不匹配:

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

我应该如何处理这些情况?

编辑:遵循AliF50的解决方案,这里是我必须做的调整(粘贴在这里而不是评论以获得更好的代码格式)以防万一

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

标签: typescriptjasminejasmine-node

解决方案


我会得到参数的句柄并断言它包含字符串。

像这样的东西:

  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());
});

推荐阅读