1-5 Provide Testing Helper Functions as Globals in JavaScript

Provide Testing Helper Functions as Globals in JavaScript

These testing utilities that we built are pretty useful. We want to be able to use them throughout our application in every single one of our test files.

Some testing frameworks provide their helpers as global variables. Let’s implement this functionality to make it easier to use our testing framework and assertion library. We can do this by exposing our test and expect functions on the global object available throughout the application.

提取码:acg6

观看视频

Code

Transcript

These testing utilities are pretty useful. We want to be able to use them throughout our application in every single one of our test files.

We could put these into a module that we would require an import into every single one of our test files, but many testing frameworks embrace the fact that you're going to be using these in every single one of your test files, and so they just make them available globally.

I am going to cut this out of our testing file. I am going to go to setup-global.js file, and I will paste it into here, and then I will say global.test = test, and global.expect = expect.

setup-globals.js

async function test(title, callback) {
  try {
    await callback()
    console.log(`✓ ${title}`)
  } catch (error) {
    console.error(`✕ ${title}`)
    console.error(error)
  }
}

function expect(actual) {
  return {
    toBe(expected) {
      if (actual !== expected) {
        throw new Error(`${actual} is not equal to ${expected}`)
      }
    }
  }
}

global.test = test
global.expect = expect

I can run

node --require ./setup-globals.js lessons/globals.js

and then our test file.

We get the same result as we did before. Now, we can use this setup-globals in every single one of our test files. With that setup, all of our test files can use the test and expect global variables.

star该项目

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,211评论 0 10
  • 2015.12.17,周四,冷,火锅店。大学室友,同在上海,半年一聚,聊天、涮肉、吹b、喝酒、吐槽、加辣、感...
    饥人谷_Oneleven阅读 3,297评论 1 5
  • 减肥是一个永远的话题。 也是一个永远的问题——成功似乎一直是暂时的,失败看上去却是永恒的。 食物热量表,已经影响了...
    健身有干货阅读 3,258评论 0 0
  • 多久没有提笔写点心情,发现提笔无力。最近,莫名其妙想辞职,想出去看看外面的世界;想创业,想流浪,想........
    伊管家阅读 1,661评论 0 0

友情链接更多精彩内容