簡體   English   中英

JEST-當我在異步方法中運行“npm run jest”時,一些測試沒有運行

[英]JEST- some of the tests are not running when I run "npm run jest" in async methods

我正在測試一個在 REDIS 中保存數據的服務,在我的描述中,我有幾個“it”測試,“it”測試正在測試一個由異步函數賦予值的​​變量,我注意到當我運行測試時“描述”看不到其中的測試套件(“它”)。 我收到這樣的錯誤:“您的測試套件必須包含至少一個測試”。 我注意到,當我刪除從異步函數獲取數據的變量行時,它確實看到了測試,但它們不相關,因為它們測試了從異步函數獲取數據的變量的值,我離開了代碼,以幫助您更好地理解我在說什么。

describe("some testing", ()=>{
describe("redisProcessor", ()=>{
    console.log("---------------------------debug2")
    aisListenerSpec.run("123456")
    aisListenerSpec.redisProcessor(JSON.stringify(validMessage));

    let isOkay = true
    aisListenerSpec.redisSetter.client.hgetall("________someString______",(err, result)=>{
        console.log("---------------------------debug3")
        for (const key in result) {
            if(validMessage[key]!==undefined)
                if(JSON.stringify(validMessage[key])!==result[key]) isOkay = false;
        }

        console.log("---------------------------debug4")

        it("________someString______${missionId} should be 2 another fields: messageTime and missionId", ()=>{
            expect(result["messageTime"]).toBeTruthy();
            expect(result["missionId"]).toBe("123456");
        })
        it("________someString______${missionId} should be the same the validMessage",  ()=>{
            console.log("---------------------------debug5")
            expect(isOkay).toBeTruthy();
        })
        console.log("---------------------------debug6")
    })
})

這是cli輸出

這是cli輸出

看來這個笑話在進行測試之前就已經結束了。

提前謝謝!

異步代碼很難考慮。 一個常見的陷阱是沒有意識到當你調用任何異步的時候,你所在的函數會立即轉到下一行代碼。 然后,在某個未來和不確定的時間,回調被調用。 也許。

這就是您調用aisListenerSpec.redisSetter.client.hgetall時代碼中發生的情況。 it的所有調用都在回調中,並且不在describe中調用。 describe已經返回之后,它們會在稍后的某個時間被調用。

此外,你們中的許多設置代碼可能應該在對beforeEach的調用中,而不是在describe 這使您可以更好地控制何時調用設置代碼並為每個測試運行它,有助於減少測試套件中的副作用。

Jest 有一個相當完整的頁面描述如何測試這樣的代碼。 如果您只是想要一個快速的解決方案,我已經綜合了幾個快速示例,它們應該會有所幫助。 😉 但我建議你去閱讀鏈接並熟悉在 Jest 中處理這個問題的方法。

選項一。 使用done 在調用done之前,設置不會返回。 如果done從未被調用,您將收到超時錯誤並且測試將失敗:

describe("test async thing", () => {

  let results

  beforeEach(done => {
    processWithCallback("foo", (err, result) => {
      if (err) { 
        done(err)
      } else {
        results = result
        done()
      }
    }
  }

  it("did a thing", () => {
    expect(result.foo).toBe('foo')
  })
})

選項二。 使用並返回一個Promise 如果Promise永遠不會解決,您將收到超時錯誤:

describe("test async thing", () => {

  let results

  beforeEach(() => {
    return new Promise((resolve, reject) => {
      processWithCallback("foo", (err, result) => {
        if (err) { 
          reject(err)
        } else {
          results = result
          resolve()
        }
      }
    }
  }

  it("did a thing", () => {
    expect(result.foo).toBe('foo')
  })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM