首页 > 解决方案 > 如何在 String 对象的原型上实现这个测试?

问题描述

如何实现这个有效的功能?

我想实现一个返回true或false的测试函数,

示例:'any-string-1'.valid('!empty'):

这是我的 valid.js 文件

function valid(str) {
  if (
    typeof str == "undefined" ||
    !str ||
    str === "" ||
    str.length < 10 ||
    !/[^\s]/.test(str) ||
    /^.*-s/i.test(str)
  ) {
    return true;
  } else if (str.length > 30) {
    return false;
  }
}
module.exports = valid;

标签: javascripttestingjestjs

解决方案


假设您使用的是 Jest,您可以使用toBe

const emptyStr = '';
const str = 'some-str';
    
expect(Boolean(emptyStr.length)).toBe(false); // it's empty, it's false because length is 0;
    
expect(str.length > 30).toBe(false); // it's false because length is not greather than 30;
    
expect(str.length < 10).toBe(true); // it's true because length is lower than 10;

推荐阅读