typescript - 如何将 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
解决方案
我会得到参数的句柄并断言它包含字符串。
像这样的东西:
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());
});
推荐阅读
- rest - 当差异在路由中时如何使用 ResponseCache 在 ASPNET Core 中缓存
- r - 在数据框中添加一个新列,其中包含开始和结束时间戳之间的天数
- elasticsearch - 使用匹配词进行弹性搜索排序(如果存在)
- php - 我可以使用 artisan serve laravel 运行多个命令吗?
- powershell - 更改 PowerShell 对象属性名称,保留值
- swift - 在 NSPopupButton 菜单中使用与主菜单相同的 keyEquivalent
- swift - 组合中的可重用发布者(订阅?)
- facebook - Facebook Graph API 服务暂时不可用错误
- html - 如何在 HTML 中设置表格并通过缩小来移动边框
- python - 在 python 中编写 for 循环或迭代以在 URL 列表上执行相同的命令?