Skip to content

牛刀小试 手机号加密

看完三个小节的课程,下面我们可以来个简单的小题目来熟悉一下TDD了。

下面是一个企业非常常见的需求

场景

产品经理:

小豪啊,运营那边反馈我们系统这边的手机号没有做加密,都是真实的手机号,我们给它做个加密吧。就像这样:157****9999 这样,中间的四位数用星号表示就好了。

小豪:

好的。这个很快。

image-20230720221327630

思考

这个确实是个非常简单的需求。就是给中间的几位数换成 * ,换平常的开发思路是不是直接就上手写代码啦?

我们现在用 TDD 的方式来写。我们需要先编写测试用例:

这个环节我们应该要把各种有可能的边界情况都考虑进去。

前端的数据大部分情况下都来源于后端,我们也不能100%相信后端的数据,人非圣贤,有时候我们接收的数据也有可能是错误的数据格式。如:和后端定义的是字符串类型,但是我们收到了number类型,或者是收到了undefined,或者null。不能让程序报错。

ts
// src/util/__test__/encryption.spec.ts
describe('>>> encryption_phone', () => {
	it('when phone is undefined', () => {
		expect(encryptionPhone(undefined)).toBe('')
	})

	it('when phone is null', () => {
		expect(encryptionPhone(undefined)).toBe('')
	})

	it("when phone is ''", () => {
		expect(encryptionPhone('')).toBe('')
	})

	it('when phone type of = number', () => {
		expect(encryptionPhone(15736379999)).toBe('157****9999')
	})

	it('when phone type of = string', () => {
		expect(encryptionPhone('15736379999')).toBe('157****9999')
	})
})
// src/util/__test__/encryption.spec.ts
describe('>>> encryption_phone', () => {
	it('when phone is undefined', () => {
		expect(encryptionPhone(undefined)).toBe('')
	})

	it('when phone is null', () => {
		expect(encryptionPhone(undefined)).toBe('')
	})

	it("when phone is ''", () => {
		expect(encryptionPhone('')).toBe('')
	})

	it('when phone type of = number', () => {
		expect(encryptionPhone(15736379999)).toBe('157****9999')
	})

	it('when phone type of = string', () => {
		expect(encryptionPhone('15736379999')).toBe('157****9999')
	})
})

基于以上的单测,我们再来进行一波编码:

ts
export function encryptionPhone(phone: any) {
	if (phone === undefined || phone === null) {
		return ''
	}
	const str = String(phone)
	return [...str]
		.map((char, index) => (index >= 3 && index <= 6 ? '*' : char))
		.join('')
}
export function encryptionPhone(phone: any) {
	if (phone === undefined || phone === null) {
		return ''
	}
	const str = String(phone)
	return [...str]
		.map((char, index) => (index >= 3 && index <= 6 ? '*' : char))
		.join('')
}

编写完以上代码,我们再运行单测,结果发现测试的结果是全部通过! image-20230720224121882

当看到这绿绿的效果测试通过,心中便觉稳健,可以放心的上线了,后端不管返回什么,都不会报错,且都是预期的返回。

总结

怎么样!通过这个小demo感觉到 TDD 的好处了吧,或者说感觉到写一些单测的好处了吧😄

总结下来大家应该会有发现有以下的好处:

  • 思考变多了

    我们提前的思考了可能性,再根据这些可能性去针对性的编码。降低了一些可能出现的bug。如没有意识到可能后端返回的数据类型错误了

  • 自己得到满足了

    看着这绿绿的pass,太爽了

  • 省心了

    上线的代码经过了我们自己的单测,基本不用担心线上问题。就算真的有,也就是自己确实编写单测那环节没做好,也是在积累经验,之后只会更好。

最后想说,确实 TDD 非常吸引人吧~ 那大家动手吧,这个demo 自己也写一遍。