Skip to content

Commit 812c57d

Browse files
xianjianlf2冼健聪43081j
authored
fix: preserve literal template tags in assertion values (#1853)
* fix: preserve literal template tags in assertion values * chore: properly type `msg` --------- Co-authored-by: 冼健聪 <[email protected]> Co-authored-by: James Garbutt <[email protected]>
1 parent 964d9a4 commit 812c57d

3 files changed

Lines changed: 37 additions & 9 deletions

File tree

‎lib/chai/utils/getMessage.js‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -37,16 +37,18 @@ export function getMessage(obj, args) {
3737

3838
if (typeof msg === 'function') msg = msg();
3939
msg = msg || '';
40-
msg = msg
41-
.replace(/#\{this\}/g, function () {
42-
return objDisplay(val);
43-
})
44-
.replace(/#\{act\}/g, function () {
45-
return objDisplay(actual);
46-
})
47-
.replace(/#\{exp\}/g, function () {
40+
msg = /** @type {string} */ (msg).replace(
41+
/#\{(this|act|exp)\}/g,
42+
function (_, tag) {
43+
if (tag === 'this') {
44+
return objDisplay(val);
45+
}
46+
if (tag === 'act') {
47+
return objDisplay(actual);
48+
}
4849
return objDisplay(expected);
49-
});
50+
}
51+
);
5052

5153
return flagMsg ? flagMsg + ': ' + msg : msg;
5254
}

‎test/expect.js‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,16 @@ describe('expect', function () {
99
expect('foo').to.equal('foo');
1010
});
1111

12+
it('preserves literal template tags in assertion values', function () {
13+
err(function () {
14+
expect('#{exp}', 'custom message').to.equal('different');
15+
}, "custom message: expected '#{exp}' to equal 'different'");
16+
17+
err(function () {
18+
expect('#{exp}').to.not.equal('#{exp}');
19+
}, "expected '#{exp}' to not equal '#{exp}'");
20+
});
21+
1222
describe('safeguards', function () {
1323
before(function () {
1424
chai.util.addProperty(chai.Assertion.prototype, 'tmpProperty', function () {

‎test/utilities.js‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -687,6 +687,22 @@ describe('utilities', function () {
687687
template: '#{this}#{act}#{exp}#{act}#{this}',
688688
expected: '\'' + objName + '\'\'' + actualValue + '\'\'' + expectedValue + '\'\'' + actualValue + '\'\'' + objName + '\''
689689
},
690+
// template tags inside substituted values remain literal
691+
{
692+
objName: '#{this} #{act} #{exp}',
693+
template: '#{this}',
694+
expected: "'#{this} #{act} #{exp}'"
695+
},
696+
{
697+
actualValue: '#{this} #{act} #{exp}',
698+
template: '#{act}',
699+
expected: "'#{this} #{act} #{exp}'"
700+
},
701+
{
702+
expectedValue: '#{this} #{act} #{exp}',
703+
template: '#{exp}',
704+
expected: "'#{this} #{act} #{exp}'"
705+
},
690706
// immune to string.prototype.replace() `$` substitution
691707
{
692708
objName: '-$$-',

0 commit comments

Comments
 (0)