簡體   English   中英

如何在 Chai 和 Postman 中測試 number 和 null 的數據類型?

[英]How to test the data-types of number and null in Chai and Postman?

我正在嘗試使用 Postman 在我的 API 測試中驗證響應的數據類型。 返回值可以是整數、浮點數或 null 我怎樣才能用 Chai 和在一個聲明中做到這一點?

這些是我在使用 javascript 和 Chai 的 Postman 測試中的簡化斷言。

    pm.expect(23).to.be.a('number'); // PASS
    pm.expect(2.3).to.be.a('number'); // PASS
    pm.expect(23).to.be.oneOf(['number', null]); // FAIL
    pm.expect(2.3).to.be.oneOf(['number', null]); // FAIL

我希望所有的斷言都能通過。 謝謝,我感謝任何評論。

所以我認為您擁有一種專門的方法,但是我不認為這種方法存在,所以我有所作為。 我沒有使用一個預定義的狀態,而是自己制作了stament並將其評估為true

這里的主要問題是typeof(null)返回“對象”,我認為這不足以作為比較

let element=[23,null,12];
  for(let e of element){

  //one statement
  pm.expect(e==null||typeof(e)=='number').to.be.true


  }

由於JavaScript中的object類型為null ,因此將測試用例寫為

pm.expect(typeof 23).to.be.oneOf(['number', 'object']);

這可能是一種簡單的方法,並且可以在簡單的檢查中使用。 但是,我建議您使用第二種方法,即使用最快的JSON模式驗證器。

var Ajv = require('ajv'),
ajv = new Ajv({logger: console}),
schema = {
    "properties": {
        "myNumber": {
            "type": ["number","null"]
        }
    }
};

pm.expect(ajv.validate(schema, {myNumber: 23})).to.be.true; 

您可以使用來自 chai 的.statify方法:

expect(1).to.satisfy(function(num) {
  return num == null || Number.isInteger(num);
});

來源

暫無
暫無

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

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