安装
npm install --save-dev jest
demo
module.exports = (a, b) => {
return a + b;
}
const sum = require('./sum');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
scripts: {
"test": "jest"
}
npm run test
esm
export default (a, b) => {
return a + b;
}
import sum from './src/sum'
describe('sum', () => {
it('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
});
npm run test
module.exports = {
presets: [
[
"@babel/preset-env",
{
targets: {
node: "current"
}
}
]
]
};
npm install --save-dev babel-jest @babel/core @babel/preset-env
scripts: {
"test": "NODE_OPTIONS=--experimental-vm-modules jest"
}
测试vue界面内容
import { mount } from '@vue/test-utils'
describe('MyComponent.vue', () => {
it('displays message', () => {
const wrapper = mount(MyComponent);
expect(wrapper.text()).toMatch('Hello, world!');
})
});
条件逻辑
describe('Foo', () => {
it('a 标签内容', () => {
const wrapper = mount(Foo);
const profile = wrapper.get('#profile');
expect(profile.text()).toBe('Profile');
});
it('查看元素是否存在', () => {
const wrapper = mount(Foo);
const admin = wrapper.find('#admin');
expect(admin.exists()).toBe(false);
});
it('存在', () => {
const wrapper = mount(Foo,{
data(){
return {
isAdmin: true
}
}
});
const admin = wrapper.find('#admin');
expect(admin.exists()).toBe(true);
});
it('是不是显示', () => {
const wrapper = mount(Foo);
const user = wrapper.find('#user');
expect(user.isVisible()).toBe(false);
});
});
事件
describe('Emit', () => {
it('点击事件', () => {
const wrapper = mount(Emit);
const button = wrapper.get('button');
button.trigger('click');
expect(wrapper.emitted()).toHaveProperty('increment');
expect(wrapper.emitted('increment')).toBetruthy();
});
it('点击事件 数据', () => {
const wrapper = mount(Emit);
const button = wrapper.get('button');
button.trigger('click');
button.trigger('click');
expect(wrapper.emitted('increment')[0]).toEqual([1]);
expect(wrapper.emitted('increment')[1]).toEqual([2]);
});
});
props
describe('Props', () => {
const wrapper = mount(Props,{
props:{
minLength: 10
}
});
const input = wrapper.get('input');
await input.setValue('123');
expect(wrapper.text()).toContain('密码不能少10位');
expect(wrapper.find("[data-test='error']").exists).toBe(true);
wrapper.setProps({
minLength: 5
});
});
slot
describe('Slot', () => {
it('插槽', () => {
const wrapper = mount(Slot,{
slots:{
default:'hello world'
}
});
expect(wrapper.text()).toContain('hello world');
});
it('插槽多个', () => {
const wrapper = mount(Slot,{
slots:{
default:["<div id='one'>one</div>","<div id='two'>two</div>"]
}
});
expect(wrapper.find("#one").text()).toContain('one');
expect(wrapper.find("#two").text()).toContain('two');
});
it('作用域插槽', () => {
const wrapper = mount(Slot,{
slots:{
header:`
<template #slot="data">
hello {{data.msg}}
</template>
`
}
});
expect(wrapper.find("header").text()).toContain('hello message');
});
});