簡體   English   中英

Mocha & Chai - 測試異步 function 在傳遞無效參數時是否拋出 TypeError?

[英]Mocha & Chai - Test if async function throws TypeError when passed invalid param?

我有這個 function:

const DEFAULT_ROLES = [
  'Director',
  'Admin',
]; // Default Policy

async function aliasIsAdmin(alias, roles = DEFAULT_ROLES) {
  const url = 'https://foobarapi.execute-api.us-west-2.amazonaws.com/foo/bar/'; 

  //How to test for this throw, for example?
  if (typeof alias !== 'string') {
    throw new TypeError(`Entity "alias" must be a string but got "${typeof alias}" instead.`); 
  }

  if (!Array.isArray(roles)) {
    throw new TypeError(`Entity "roles" must be an array but got "${typeof roles}" instead.`);
  } else if (roles.some((role) => typeof role !== 'string')) {
    throw new TypeError(`Entity "roles" must be an array of strings but got at least one element of type: "${typeof roles}" instead.`);
  }

  const { data } = (await axios.get(url + alias)); // Fetch roles that the alias holds.
  return data.some((role) => roles.includes(role));
}

當傳遞無效參數時,如何使用 Mocha 和 Chai 測試 function 是否拋出?

例如, async function aliasIsAdmin()應該拋出TypeError: Entity "alias" must be a string but got "undefined" instead. 因為該特定調用的alias參數undefined

如果我做:

it('throws TypeError when alias param is not typeof "string"', async () => {
    assert.throws(async function () { await aliasIsAdmin() }, TypeError, /must be string/);
}); 

我得到:

aliasIsAdmin
    1) throws TypeError when alias param is not typeof "string"
(node:77600) UnhandledPromiseRejectionWarning: TypeError: Entity "alias" must be a string 
but got "undefined" instead.
[... stacktrace continues ...]

  1) aliasIsAdmin
   throws TypeError when alias param is not typeof "string":
 AssertionError: expected [Function] to throw TypeError
  at Context.<anonymous> (test/permissions-manager-client.test.js:25:16)
  at processImmediate (internal/timers.js:439:21)
  at process.topLevelDomainCallback (domain.js:130:23)

我找不到帶有async函數的示例,所以我想這就是它不起作用的原因。

有針對這個的解決方法嗎?

嘗試將其包裝在try/catch中,因為它會拋出Error

it('throws TypeError when alias param is not typeof "string"', async () => {
    try {
        await aliasIsAdmin();
    } catch(error) {
        // Do your assertion here
        expect(error).to.be.an('error');
        expect(error.name).to.be.equal('TypeError');
        expect(error.message).to.be.equal('Entity "alias" must be a string but got "undefined" instead.');
    }
}); 

(或者)

編輯

it('throws TypeError when alias param is not typeof "string"', async () => {
    await expect(aliasIsAdmin()).to.be.rejectedWith(TypeError);
}); 

(最后)為了更完整的解決方案,可以測試一條消息:

it('throws TypeError when alias param is not typeof "string"', async () => {
    await expect(aliasIsAdmin()).to.be.rejectedWith(TypeError, 'Entity "alias" must be a string but got "undefined" instead.');
}); 

對於沒有.rejectedWith()的以前的 chai 版本。 處理的唯一異步測試方法是將其包裝在 try catch 中並檢查expect catch 中的錯誤。

  it('should fail', async () => {
          try{
            await failingPromise();
          }catch(err){
            expect(err).to.exist
            const { message }=err
            expect(message).to.contain("error message")
            return
          }
        //if there is no error from promise throw one here
         throw new Error("should throw")
    });

暫無
暫無

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

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