index.spec.js 1.97 KB
import { createLocalVue, shallowMount } from "@vue/test-utils";

const VariableTextarea = require("./index.vue").default;

describe("marketingPushStrategy components/variableTextarea", () => {
	const localVue = createLocalVue();
	let wrapper;

	function createWrapper(propsData = {}) {
		wrapper = shallowMount(VariableTextarea, {
			localVue,
			propsData: {
				value: "您好",
				variableList: [{ code: "customerName", name: "客户姓名" }],
				...propsData,
			},
			stubs: {
				"el-input": true,
				"el-dropdown": true,
				"el-dropdown-menu": true,
				"el-dropdown-item": true,
			},
		});
		return wrapper;
	}

	afterEach(() => {
		if (wrapper) {
			wrapper.destroy();
		}
		jest.clearAllMocks();
	});

	it("handleInput 应直接透传输入内容", () => {
		createWrapper();

		wrapper.vm.handleInput("新的内容");

		expect(wrapper.emitted("input")[0]).toEqual(["新的内容"]);
	});

	it("handleCommand 应在光标位置插入变量", async () => {
		createWrapper({ value: "您好,欢迎" });
		const textarea = {
			selectionStart: 2,
			selectionEnd: 2,
			setSelectionRange: jest.fn(),
			focus: jest.fn(),
		};
		Object.defineProperty(wrapper.vm, "$refs", {
			configurable: true,
			value: {
				textareaRef: {
					$el: {
						querySelector: jest.fn(() => textarea),
					},
				},
			},
		});

		wrapper.vm.handleCommand("客户姓名");
		await wrapper.vm.$nextTick();

		expect(wrapper.emitted("input")[0]).toEqual(["您好{{客户姓名}},欢迎"]);
		expect(textarea.setSelectionRange).toHaveBeenCalledWith(10, 10);
		expect(textarea.focus).toHaveBeenCalled();
	});

	it("找不到 textarea 时应在末尾追加变量", () => {
		createWrapper({ value: "您好" });
		Object.defineProperty(wrapper.vm, "$refs", {
			configurable: true,
			value: {
				textareaRef: {
					$el: {
						querySelector: jest.fn(() => null),
					},
				},
			},
		});

		wrapper.vm.handleCommand("客户姓名");

		expect(wrapper.emitted("input")[0]).toEqual(["您好{{客户姓名}}"]);
	});
});