我是 Jest 新手,正在尝试运行我的第一个测试。我找不到元素#app。我已将我的应用程序安装在 main.js 文件中,ID 为“app”。我正在使用 localVue 挂载在规范文件中。但是在编译时它会触发主js并尝试找到id“app”。以下是我的规格文件
// Libraries
import Vuetify from 'vuetify'
import Vuex from "vuex";
import Vue from "vue";
// Components
import home from "@/views/pages/home.vue";
// Utilities
import { createLocalVue, mount, shallowMount } from '@vue/test-utils';
describe("home.vue", () => {
let vuetify, localVue;
let store;
beforeEach(() => {
const div = document.createElement('div');
div.setAttribute('id', 'app');
document.body.appendChild(div);
localVue = createLocalVue();
localVue.use(Vuex);
vuetify = new Vuetify()
store = new Vuex.Store({
state: {},
actions: {},
mutations: {},
});
})
afterEach(() => {
const div = document.getElementById('app');
if (div) {
document.body.removeChild(div);
}
});
it("check submit button is disabled if fields are empty", async () => {
const wrapper = mount(home, {
attachTo: document.getElementById('app') ,
localVue,
vuetify,
store,
stubs: ["router-link", "router-view"],
})
const name = "";
wrapper.find(".dname").setData(name);
await Vue.nextTick();
expect(wrapper.vm.decoderName).toBe(name);
expect(wrapper.vm.isValidForm).toBeFalsy();
expect(wrapper.find(".createBtn").element.disabled).toBe(true);
});
});
我通过添加安装文件使其工作
在 jest.conf.js 文件中添加一个安装文件。
setupFiles: ['<rootDir>/test/unit/setup']
创建 setup.js 并创建 div。
createAppDiv();
function createAppDiv() {
var app = document.createElement('div');
app.setAttribute('id', 'app');
document.body.appendChild(app);
}
现在运行测试,错误就会消失。