0
点赞
收藏
分享

微信扫一扫

jest在已有项目中的安装与使用


简单的jest使用配置:

npm init -y
npm i jest@24.8.0 -D

npx jest --init 生成初始化配置
一个index文件,里面可以写入一些方法,作为测试

这个jest.config.js是自动生成的!!!!!
index.test.js就是些测试用例的文件。jest会自动的查找执行。

执行这个npm run test
这个就会执行测试用例。
当测试用例是一个ts文件的时候:添加这个参数类型限制就会出错,暂时不知道是为啥
可以在tsconfig.json里加上"noImplicitAny": false,先跳过这测试过程中的报错。

执行代码覆盖率代码
npx jest --coverage
会生成报告显示到文件夹中这个测试集合。
配置一下:在package。json中写:"coverage":"jest --coverage"
可以执行这个:npm run coverage或者yarn coverage

jest初始你初始时只支持commonjs语法,后面的es6语法需要配置。
yarn add @babel/core@7.4.5 @babel/preset-env@7.4.5 --dev

添加转换器:
​​​.babelrc​​文件。(根)

{
"presets": [
[
"@babel/preset-env",{
"targets":{
"node":"current"
}
}
]
]
}

执行就是:

npm run test // "test": "jest --watchAll",
npm run coverage//需要配置"coverage": "jest --coverage"
yarn coverage//需要配置"coverage": "jest --coverage"

执行测试用例

// const {fun} = require("../src/other/index");
import {fun} from "../src/other/index"
test("测试第一个函数",()=>{
expect(fun(30)).toBe(30)
})

以上用例就可以实现对ts函数和js函数的基本测试用例的实现。

组件的测试用例,必须考虑到使用vue的一些测试开发依赖。

项目转到系统控制台执行:​​vue add @vue/cli-plugin-unit-jest​​​ 配置:
jest.config.js文件

module.exports = {
preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel',
coverageDirectory: "coverage",//代码覆盖率生成的文件夹名
clearMocks: true,//清除数据
}

测试一个函数的报错显示

jest在已有项目中的安装与使用_ecmascript

  • 通过这个describe意思为套件,或者理解为创建一个测试集
  • it 断言
  • expect 期望
  • test 测试,类似it

    expect(wrapper.text()).toMatch(“我爱你”)
    expect(wrapper.text()).toEqual(“我爱你”)

describe('HelloWorld.vue', () => {
it('renders props.msg when passed', () => {
const wrapper = mount(HelloWorld); //Mount获取组件的包裹器,可以理解Wie就是最外层的那个div的加强版。
console.log(wrapper.text());//输出这个组件的所有的文字内容值
expect(wrapper.text()).toMatch("我爱你") /* 判断期望值符合这个正则选项否 */
})
})

vue-property-decorator使用方法如下:

​​https://zhuanlan.zhihu.com/p/191443950​​

jest在已有项目中的安装与使用_测试用例_02


对组件中的某个功能进行验证。

  • ​wrapper.text()​​//输出这个组件的所有的文字内容值
  • ​wrapper.vm.count​​//访问实际的 Vue 实例
  • ​wrapper.contains('button')​​//检测是存在button按钮
  • ​wrapper.find()​​ 定位该按钮,此方法返回一个该按钮元素的包裹器
  • 包裹器调用 ​​.trigger()​​ 来模拟点击。

​​参考​​

测试包含有element组件的。vue文件

import { shallowMount,mount,createLocalVue } from '@vue/test-utils'
import ElementUI from 'element-ui';
const localVue = createLocalVue();
localVue.use(ElementUI);


import other from "../../../src/components/other.vue"
describe('第二个文件测试', () => {
it('测试other组件', () => {
const wrapper = mount(other)
expect((wrapper.vm as any).data).toEqual(123)
})
it('测试是否有el-button按钮',()=>{
const wrapper = shallowMount(other,{localVue});
const el_btn = wrapper.find('#el_btn');
expect(el_btn.exists()).toBe(true)
})
})


举报

相关推荐

0 条评论