通过 Jest 学习 node url 模块

576 阅读1分钟

目标

  • 学习 nodejs url 模块,我们通过 jest 测试的方式来学习 url 模块
  • 时间 jest 基本功能

jest 配置

推荐全局安装 Jest, 然后就可以快乐的使用 Jest 了。

yarn init -y
yarn global add jest

cd /<workspace>

在 package.json 中添加脚本:

"scripts": {
    "jest": "jest ./index.test.js --watch"
  }

创建 Jest 文件

测试 1 + 1 = 1

const url = require('url')

const a = 1

test('should 1 = 1 ', () => {
  expect(a).toBe(1)
})

测试:指定 url 通过 url.URL 实例化后相等

test('should url.URL instance to string', () => {
  const a = `http://www.baidu.com/`
  expect(new url.URL(a).toString()).toEqual(a)
})

测试:url 协议 protocol

test('should protocol http', () => {
  const a = `http://www.baidu.com/`
  expect(new url.URL(a).protocol).toBe('http:')
})

测试:url 主机名 hostname

test('should host www.baidu.com', () => {
  const a = `http://www.baidu.com/`
  expect(new url.URL(a).hostname).toBe('www.baidu.com')
} )

测试:url 端口名和主机名

test('should hostname and port www.baidu.com:8080', () => {
  const a = `http://www.baidu.com:8080/`
  expect(new url.URL(a).hostname).toBe('www.baidu.com')
  expect(new url.URL(a).port).toBe("8080")
})

测试: url 中的路径和查询参数

test("should path and path`s search path and query", () => {
  const a = `http://www.baidu.com:8080/abc`
  expect(new url.URL(a).pathname).toBe('/abc')

  const b = `http://www.baidu.com:8080/abc/bgh`
  expect(new url.URL(b).pathname).toBe('/abc/bgh')

  const c = `http://www.baidu.com:8080/abc/bgh?a=123&b=345`
  expect(new url.URL(c).search).toBe("?a=123&b=345")
  console.log(new url.URL(c).searchParams)
})

测试:url 中的 hash

test("should hash is one", () => {
  const d = `http://www.baidu.com:8080/abc/bgh?a=123&b=345#909`
  expect(new url.URL(d).hash).toBe('#909')
})

测试 WHATWG 协议中的 user 和 password

test("should whatwg user and password", () => {
  const e = `http://mag:gam@www.baidu.com:8080/abc/bgh?a=123&b=345#909`

  expect(new url.URL(e).username).toBe('mag')

  expect(new url.URL(e).password).toBe('gam')
  expect(new url.URL(e).href).toBe("http://mag:gam@www.baidu.com:8080/abc/bgh?a=123&b=345#909")
})

参考

  1. Jest
  2. Node URL