在 beforeEach 块中初始化变量后自动建议不工作

Auto suggest not working after initialising a variable in beforeEach block

自动建议不适用于 beforeEach 块中声明的任何变量。如果我在 it() 块中使用“app”变量,自动建议不会显示任何方法。自动提示在 beforeEach 块中工作。按 Ctrl + Space 它会显示所有可用的方法。我正在使用 visual studio 代码作为 IDE。 Mocha 是测试框架。

var express = require('express')

describe("#1", async () => {

    let app 

    beforeEach("SetUp", async () => {       
        app = express();   
        app. // First,  Auto suggest is working on pressing Ctrl + Space
    })

    it("Demo Test #1.1", async () =>{

        app.  //Second, Auto suggest not working on pressing Ctrl + Space
       
   })

})

编辑:如果你不想all-in和TypeScript, you can do this using JSDoc,只要您不介意在声明 un-inferrable 变量的地方添加 @type 注释。

const express = require("express")

describe("#1", async () => {
  /** @type {express.Express} */
  let app

  beforeEach("SetUp", () => { app = express() })

  it("Demo Test #1.1", async () => {
    app // autocomplete is now available here
  })
})

原回答如下

VS Code 无法推断有关回调中设置的变量的类型信息。

考虑以下简化示例:

let variable

foo(() => {       
    variable = 1
})

bar(() => {       
    variable = 'str'
})

main(() =>{
    // what type is `variable` here?
})

如果你愿意切换到 TypeScript,这可以通过在声明中添加注释来解决:

let app: Express

演示

const nonDeterministicTimeout = () =>
    cb => setTimeout(cb, Math.random() * 100)

for (let i = 0; i < 10; ++i) {
    const foo = nonDeterministicTimeout()
    const bar = nonDeterministicTimeout()
    const main = nonDeterministicTimeout()

    let variable

    foo(() => {       
        variable = 1
    })

    bar(() => {       
        variable = 'str'
    })

    main(() =>{
        console.log(typeof variable)
        // fluctuates arbitrarily between
        // undefined, string, and number
    })
}