javascript indexOf奇怪的行为

时间:2016-08-17 05:04:50

标签: javascript string mocha indexof chai

在为我的javascript程序编写一段测试代码时,我发现了一种奇怪的无法解释的行为。我正在比较res.body的输出以检查它是否包含字符串。

更确切地说,我正在检查res.body是否包含字符串'channel'。

即使输出确实包含该字符串,测试用例总是失败。我以调试模式运行程序,以检查它失败的原因。至少可以说,结果令人费解。

> res.body
'Error: invalid channnel'
> res.body.indexOf('channel')
-1
> res.body.indexOf('channe')
-1
> res.body.indexOf('chann')
15
> 

如果我尝试在res.body中检查'channel'的indexOf,其值为'Error:invalid channel',我应该得到一个正值,但它给出了-1。

所以,我尝试减少号码。在匹配中的字符,它仍然失败,直到我减少搜索字符串以包含'chann',即省略'el'。

但是这种行为不会发生,如果我采取字符串并进行相同的练习。例如,以下工作完美。

> 'Error: invalid channel'.indexOf('channel')
15

我继续检查res.body的类型,它显示为字符串,而不是任何对象。

> typeof res.body
'string'
> 

有没有人遇到过类似的问题?或者有解释吗?

修改 它发生在我由mocha + chai框架生成的res.body。完整代码如下:

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

2 个答案:

答案 0 :(得分:3)

Private Sub CommandButton1_Click() Dim IE As Object, r as integer Dim wb as Workbook, ws as Worksheet Dim dd as String, c as Variant, found as Boolean 'Create InternetExplorer Object Set IE = CreateObject("InternetExplorer.Application") 'create other objects Set wb = ThisWorkbook Set ws = wb.Worksheets("Sheet1") ' You can uncoment Next line To see form results IE.Visible = False 'START LOOP ' URL to get data from For r = 2 To 3 debug.print ws.Range("A" & r).Value 'see what the url is IE.navigate ws.Range("A" & r).Value Do while IE.ReadyState <> 4: DoEvents: Loop 'page loaded. ' Runs loops to look for the value within the classname, if classname alternates it will change the element, if null it will exit found = false For each c in Array("vk_sh vk_bk", "_Xbe") On Error Resume Next dd = IE.document.getElementsByClassName(c)(0).innerText On Error GoTo 0 If Len(dd) > 0 Then found = true End If If found Then ws.Range("C" & r).Value = dd dd = "" 'need to set to nothing or it will retain the value. Exit For End If Next c Next r IE.Quit 'Clean up Set IE = Nothing End Sub res.body {3} channel

  

&#39;错误:无效的channnel&#39;

这意味着n匹配,但chann因为额外channe而赢了。

答案 1 :(得分:0)

在第一段代码中,&#34; channnel&#34;有3个人。这就是为什么它匹配&#34; chann&#34;但不是&#34; channe&#34;。

相关问题