I found a strange unexplainable behavior while writing a piece of test code for my javascript program. I was comparing an output of res.body to check if it contains a string.
More precisely, I was checking if res.body contained a string 'channel'.
Even though the output did really contain that string, the test case was always failing. I ran the program in debug mode, to examine why it is failing. The results are puzzling, to say the least.
> res.body
'Error: invalid channnel'
> res.body.indexOf('channel')
-1
> res.body.indexOf('channe')
-1
> res.body.indexOf('chann')
15
>
if I try to check indexOf of 'channel' in res.body whose value was 'Error: invalid channel', I was supposed to get a positive value, but it gives -1.
so, I tried by reducing the no. of chars in the match, it still fails until I reduce the search string to contain just 'chann' ie by omitting 'el'.
But this behavior doesn't happen, if I take a string litteral and do the same exercise. For example, the below works perfectly.
> 'Error: invalid channel'.indexOf('channel')
15
I went ahead and checked the typeof res.body, and it shows as string, and not any object.
> typeof res.body
'string'
>
Did anyone face a similar problem ever? Or is there an explanation to this?
EDIT It happens when I res.body as produced by mocha + chai framework. The full code is below:
58 it ("Should fail with 400, if invalid channel", function(done) {
59 chai.request(app).post('/campaigns/js')
60 .send(samples.type0.invalidChannel)
61 .end(function(err, res) {
62 console.log("response:", res.body);
63 expect(res).to.have.status(400);
>64 debugger;
65 expect(res.body).to.contain('channel');
66 return done();
67 });
68 });
You're res.body
has channel
with 3 n
s.
'Error: invalid channnel'
This means that chann
matches, but channe
won't because of the extra n
.
In the first piece of code, "channnel" has 3 n's. That's why it matched "chann" but not "channe".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.