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:
Main.vue
<template>
<div id="app">
<HelloWorld msg="Basic App"/>
</div>
</template>
HelloWorld.vue
<template>
<div class="hello">
<h1></h1>
<div v-if="images.length > 0" class="img-container">
<img
loading="lazy"
width="300"
height="300"
v-for="(item, idx) in images"
:src="item.url"
:key="idx"
/>
</div>
<br />
<button v-on:click="refreshImg()">Refresh</button>
</div>
</template>
<script>
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();
}
}
};
</script>
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?
Aucun commentaire:
Enregistrer un commentaire