Jest - VUE - UT

初始化组件

const wrapper = shallowMount(Blank, {
propsData: { desc }
})
// 对比文字
expect(wrapper.text()).toMatch(desc)

属性检查

const wrapper = mount(Button, {
propsData: {
handle: mockCallback
}
});
const handlerProps: { [key: string]: any } | undefined =
wrapper.vm.$options.props;
expect(handlerProps!.handle!.required).toBe(true);

事件是否触发

const mockCallback = jest.fn()
const wrapper = mount(Button, {
propsData: {
handle: mockCallback
}
})
wrapper.find("button").trigger("click")
expect(mockCallback).toBeCalled()
jest.clearAllMocks()

computed 验证

const wrapper: any = shallowMount(Button, {
propsData: {
handle: mockCallback
}
})
expect(wrapper.vm.colorStyle).toMatchObject({
"background-color": "#51ddab"
})

style 验证

const wrapper: any = shallowMount(Button, {
propsData: {
handle: mockCallback,
color: "red"
}
})

expect(wrapper.element.style["background-color"]).toBe("red")

多个元素的选取

list.forEach((v, i) => {
expect(
wrapper
.findAll("li")
.at(i)
.text()
).toBe(v)
})

emit 验证

const wrapper = shallowMount(CultureTabbar, {
propsData: {
index: 3
}
})

const stub = jest.fn()
wrapper.vm.$on("update:index", stub)
wrapper
.findAll("li")
.at(3)
.trigger("click")

expect(stub).toBeCalledWith(3)

元素的存在性

expect(
wrapper
.find(".f-right")
.find(".uncheck")
.exists()
).toBeTruthy()

元素的可见性

expect(wrapper.find(".grade-wrapper-edit").isVisible()).toBe(true)

主动触发事件

wrapper.trigger("click")

路由触发

it("getMyConfirmed", async next => {
const stub = jest.fn();
const $router = {
push: stub
};
// mock ajax
jest.doMock("@/constants/API", () => ({
getMyConfirmed: jest.fn(() =>
Promise.resolve({
name: "张三",
end_time: "2018",
superior: "上级",
scores: [{ case: "2", score: 4 }],
advantage: "advantage",
promotion: "promotion",
can_submit: 0
})
)
}));
const Confirm = require("@/components/modules/My/Confirm/index.vue")
.default;
const wrapper = mount(Confirm, {
mocks: {
$router
}
});
await (wrapper as any).vm.getConfirmed();

wrapper.vm.$nextTick(() => {
expect((wrapper as any).vm.feedback).toEqual(["advantage", "promotion"]);
expect((wrapper as any).vm.name).toEqual("张三");
expect((wrapper as any).vm.superior).toEqual("上级");
expect((wrapper as any).vm.end_time).toEqual("2018");
expect((wrapper as any).vm.canHandle).toEqual(0);

expect(wrapper.find(".handle button").text()).toBe(COMPLAINT);
next();
});
});

图片引入

// 需要require后对比
const unchecked = require("@assets/img/icon/unchecked.png")
const checked = require("@assets/img/icon/checked.png")

主动调用 method

expect((wrapper.vm as any).cardType(p)).toBe("refuse");

slot 验证

const wrapper = shallowMount(Modal, {
propsData: {
showModal: true
},
slots: {
footer: '<div class="fake-footer"></div>'
}
})

expect(wrapper.find(".modal-footer button").exists()).toBeFalsy()
expect(wrapper.find(".modal-footer .fake-footer").exists()).toBeTruthy()