I'm about to test the updated data images on the first-page load which i called an ajax through a method. I made the test mock for the ajax call, but it's still failed, here is my test:

主线

HelloWorld.vue

{{ msg }}

loading="lazy"

width="300"

height="300"

v-for="(item, idx) in images"

:src="item.url"

:key="idx"

/>

Refresh

import axios from "axios";

export default {

props: {

msg: String

},

data: function() {

return {

images: []

};

},

mounted() {

this.apiFetch();

},

methods: {

apiFetch() {

axios

.get("https://api.thecatapi.com/v1/images/search")

.then(val => (this.images = val.data));

},

refreshImg() {

this.apiFetch();

}

}

};

HelloWorld.spec.js

import { mount } from "@vue/test-utils";

import HelloWorld from "../HelloWorld.vue";

const $axios = {

get: () => {

return Promise.resolve({

data: [

{

breeds: [],

id: "MTY0Njk3MQ",

url: "https://cdn2.thecatapi.com/images/MTY0Njk3MQ.jpg",

width: 400,

height: 426

}

]

});

}

};

describe("HelloWorld.vue", () => {

let wrapper;

test("renders header when passed msg prop as string", () => {

const msg = "new header";

wrapper = mount(HelloWorld, {

propsData: { msg }

});

expect(wrapper.contains("h1")).toBe(true);

expect(wrapper.props().msg).toBe("new header");

expect(wrapper.text()).toMatch(msg);

});

test("renders an image when button is clicked", () => {

const images = [

{

breeds: [],

id: "XrrbdqDvw",

url: "https://cdn2.thecatapi.com/images/XrrbdqDvw.jpg",

width: 1138,

height: 1138

}

];

const refreshImg = jest.fn();

wrapper = mount(HelloWorld, {

data() {

return { images };

}

});

wrapper.setMethods({ refreshImg });

wrapper.find("button").trigger("click");

expect(refreshImg).toHaveBeenCalled();

expect(wrapper.find(".img-container").isVisible()).toBe(true);

expect(wrapper.find(`img[src="${images[0].url}"]`).isVisible()).toBe(true);

});

test("renders image container on the first load", () => {

// === test failed here! ===

wrapper = mount(HelloWorld, { mocks: { $axios } });

expect(wrapper.find(".img-container").exists()).toBe(true);

});

});

I tried to check wrapper.vm.$data.images inside the renders image container on the first load test case, the images still empty. Am i doing it wrong?

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐