如何让Jasmine测试忽略多行字符串中的缩进
解决Jasmine测试中多行字符串缩进不匹配的问题
一、用现成的字符串处理库
常用的dedent和strip-indent都是专门处理多行模板字符串缩进的工具,完全能满足你的需求:
以dedent为例:
- 安装依赖:
npm install dedent --save-dev
- 在测试文件中导入并使用:
import dedent from 'dedent'; it('should get the proper data', () => { expect(service.getData('foo')).toEqual(dedent` example line 1 example line 2 example line 3 `); });
它会自动移除所有行的公共缩进,同时保留换行和行内的相对缩进,效果和你想要的safeUnindent完全一致。
二、自行实现轻量工具函数
不想加外部依赖的话,写个简单函数就能搞定:
function safeUnindent(str) { // 取出所有非空行 const lines = str.trim().split('\n'); // 计算所有行的最小缩进量 const minIndent = Math.min(...lines.map(line => { const indentMatch = line.match(/^\s+/); return indentMatch ? indentMatch[0].length : 0; })); // 移除每一行的最小公共缩进并拼接 return lines.map(line => line.slice(minIndent)).join('\n'); }
测试里直接调用即可:
it('should get the proper data', () => { expect(service.getData('foo')).toEqual(safeUnindent(` example line 1 example line 2 example line 3 `)); });
这个函数会自动处理公共缩进,还能保留行内的相对缩进(比如第二行多出来的空格会被保留)。
三、扩展Jasmine匹配器
如果大量测试都需要这个功能,可以扩展Jasmine的匹配器,让断言更简洁:
beforeEach(() => { jasmine.addMatchers({ toEqualUnindented: function() { return { compare: function(actual, expected) { const processedExpected = safeUnindent(expected); return { pass: actual === processedExpected, message: `Expected '${actual}' to equal unindented '${processedExpected}'` }; } }; } }); });
之后测试里就能这么写:
it('should get the proper data', () => { expect(service.getData('foo')).toEqualUnindented(` example line 1 example line 2 example line 3 `); });
内容的提问来源于stack exchange,提问作者Chris Barr
相关产品推荐
相关产品推荐

