51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 1502|回复: 0
打印 上一主题 下一主题

[原创] jest 如何从0-1搭建单元测试?

[复制链接]
  • TA的每日心情
    无聊
    14 小时前
  • 签到天数: 936 天

    连续签到: 3 天

    [LV.10]测试总司令

    跳转到指定楼层
    1#
    发表于 2022-9-29 14:09:59 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    安装依赖
    1. <font size="3">cnpm install ts-jest jest  @types/jest --save-dev</font>
    复制代码
    配置
      1、修改package.jsoin,在"scipts"添加"test": "jest", 如下:

    1. <font size="3">"scripts": {

    2.       "start": "webpack-dev-server",

    3.       "build": "webpack --mode production",

    4.       "test": "jest"

    5.   }</font>
    复制代码
    2、添加一个jest.config.js文件
      填入如下内容:

    1. <font size="3">module.exports = {

    2.       "moduleFileExtensions": [

    3.           "js",

    4.           "ts",

    5.           "tsx"

    6.       ],

    7.       "transform": {

    8.           "^.+\\.tsx?[        DISCUZ_CODE_2        ]quot;: "ts-jest",

    9.       },

    10.       "testMatch": [

    11.           "<rootDir>/tests/**/*.ts?(x)"

    12.       ]

    13.   }</font>
    复制代码
    通过testMatch可以看到我们是检测 工程/tests/ 文件下的内容。一般是推荐在文件下面写测试文件,但是我比较喜欢在外面写。然后添加一个测试文件。
      添加测试文件


    这是我的目录,可以参考。
      编写测试
      参考下QAQ  具体看官方文档 jestjs.io/docs/zh-Han…

    1. <font size="3">import { getSTyleStr, id } from '../../src/utils/utils'

    2.   test('id', () => {

    3.       expect(id(1)).toBe(1)

    4.       expect(id(null)).toBe(null)

    5.       expect(id(void 0)).toBe(void 0)

    6.   })

    7.   describe('css class utils getSTyleStr', () => {

    8.       it('带大写的属性', () => {

    9.           expect(getSTyleStr({backgroundColor: "rgba(216,52,52,1)"}))

    10.           .toBe('background-color: rgba(216,52,52,1);')

    11.       })

    12.       it('单个属性', () => {

    13.           expect(getSTyleStr({width: "30px", height: "30px"}))

    14.           .toBe('width: 30px;height: 30px;')

    15.       })

    16.   })</font>
    复制代码
    查看效果
    1. <font size="3">npm run test</font>
    复制代码

    如果我们写错了,这时候:


    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing

    x
    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-4-24 23:17 , Processed in 0.066404 second(s), 24 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表