Merge vuex-store branch

This commit is contained in:
2020-12-18 06:15:24 +01:00
8 changed files with 145 additions and 84 deletions

View File

@@ -1,21 +1,18 @@
module.exports = { module.exports = {
moduleNameMapper: { moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1', "^@/(.*)$": "<rootDir>/$1",
'^~/(.*)$': '<rootDir>/$1', "^~/(.*)$": "<rootDir>/$1",
'^vue$': 'vue/dist/vue.common.js' "^vue$": "vue/dist/vue.common.js"
}, },
moduleFileExtensions: [ moduleFileExtensions: ["js", "vue", "json"],
'js',
'vue',
'json'
],
transform: { transform: {
'^.+\\.js$': 'babel-jest', "^.+\\.js$": "babel-jest",
'.*\\.(vue)$': 'vue-jest' ".*\\.(vue)$": "vue-jest"
}, },
coverageDirectory: "<rootDir>/coverage",
collectCoverage: true, collectCoverage: true,
collectCoverageFrom: [ collectCoverageFrom: [
'<rootDir>/components/**/*.vue', "<rootDir>/components/**/*.vue",
'<rootDir>/pages/**/*.vue' "<rootDir>/pages/**/*.vue"
] ]
} };

View File

@@ -1,7 +1,6 @@
import { mount } from "@vue/test-utils"; import { mount, createLocalVue } from "@vue/test-utils";
import axios from "axios"; import Vuex from "vuex";
import Film from "./_id"; import Film from "./_id";
import mockFilms from "@/test/fake-films.json";
let $route = { let $route = {
path: "/films", path: "/films",
@@ -10,15 +9,24 @@ let $route = {
} }
}; };
const mockFilm = mockFilms.filter(o => o.id === $route.params.id); const localVue = createLocalVue();
localVue.use(Vuex);
jest.mock("axios", () => ({
$get: jest.fn(() => mockFilm)
}));
describe("Film page", () => { describe("Film page", () => {
let state, actions, store;
beforeEach(() => {
state = {
film: {}
};
actions = {
getFilm: jest.fn()
};
store = new Vuex.Store({ state, actions });
});
it("should render Film page instance", () => { it("should render Film page instance", () => {
const wrapper = mount(Film); const wrapper = mount(Film, { localVue, store });
expect(wrapper.exists()).toBe(true); expect(wrapper.exists()).toBe(true);
}); });
@@ -36,31 +44,13 @@ describe("Film page", () => {
).toBe(false); ).toBe(false);
}); });
it("should get film from Ghibli API", async () => { it("should dispatch getFilm action", async () => {
let wrapper = mount(Film, { let wrapper = mount(Film, {
mocks: { localVue,
$route, store
$axios: axios
}
}); });
expect( await wrapper.vm.$options.asyncData({ store, params: $route.params });
( expect(actions.getFilm).toHaveBeenCalled();
await wrapper.vm.$options.asyncData({
$axios: axios,
params: $route.params
})
).film
).toEqual(mockFilm);
// // Init page with mocked asyncData
// wrapper = shallowMount(Film, {
// mocks: {
// films: (await wrapper.vm.$options.asyncData(wrapper.vm)).films,
// $axios: axios
// }
// });
// expect(wrapper.findComponent({ name: "Grid" }).exists()).toBe(true);
}); });
}); });

View File

@@ -5,6 +5,8 @@
</template> </template>
<script> <script>
import { mapState } from "vuex";
export default { export default {
name: "Film", name: "Film",
head() { head() {
@@ -18,14 +20,11 @@ export default {
); );
return uuid.test(params.id); return uuid.test(params.id);
}, },
async asyncData({ $axios, params }) { async asyncData({ params, store }) {
const film = await $axios.$get(`/api/films/${params.id}`); await store.dispatch("getFilm", params.id);
return { film };
}, },
data() { computed: {
return { ...mapState(["film"])
film: {}
};
} }
}; };
</script> </script>

View File

@@ -1,37 +1,36 @@
import { mount, shallowMount } from "@vue/test-utils"; import { mount, shallowMount, createLocalVue } from "@vue/test-utils";
import axios from "axios"; import Vuex from "vuex";
import FilmsView from "./"; import Films from "./";
import mockFilms from "@/test/fake-films.json";
jest.mock("axios", () => ({ const localVue = createLocalVue();
$get: jest.fn(() => mockFilms) localVue.use(Vuex);
}));
describe("Films page", () => { describe("Films page", () => {
let state, actions, store;
beforeEach(() => {
state = {
films: []
};
actions = {
getFilms: jest.fn()
};
store = new Vuex.Store({ state, actions });
});
it("should render Films page instance", () => { it("should render Films page instance", () => {
const wrapper = mount(FilmsView); const wrapper = mount(Films, { store, localVue });
expect(wrapper.find("img").exists()).toBe(true); expect(wrapper.find("img").exists()).toBe(true);
}); });
it("should get films from Ghibli API", async () => { it("should dispatch getFilms action", async () => {
let wrapper = shallowMount(FilmsView, { let wrapper = shallowMount(Films, {
mocks: { store,
$axios: axios localVue
}
});
expect((await wrapper.vm.$options.asyncData(wrapper.vm)).films).toEqual(
mockFilms
);
// Init page with mocked asyncData
wrapper = shallowMount(FilmsView, {
mocks: {
films: (await wrapper.vm.$options.asyncData(wrapper.vm)).films,
$axios: axios
}
}); });
await wrapper.vm.$options.asyncData({ store });
expect(actions.getFilms).toHaveBeenCalled();
expect(wrapper.findComponent({ name: "Grid" }).exists()).toBe(true); expect(wrapper.findComponent({ name: "Grid" }).exists()).toBe(true);
}); });
}); });

View File

@@ -11,6 +11,7 @@
<script> <script>
import Grid from "@/components/Grid"; import Grid from "@/components/Grid";
import { mapState } from "vuex";
export default { export default {
name: "Films", name: "Films",
@@ -18,14 +19,11 @@ export default {
head: { head: {
titleTemplate: "%s - Films" titleTemplate: "%s - Films"
}, },
async asyncData({ $axios }) { async asyncData({ store }) {
const films = await $axios.$get("/api/films"); await store.dispatch("getFilms");
return { films };
}, },
data() { computed: {
return { ...mapState(["films"])
films: []
};
} }
}; };
</script> </script>

34
store/index.js Normal file
View File

@@ -0,0 +1,34 @@
export const state = () => ({
films: [],
film: {}
});
export const mutations = {
setFilms: (state, films) => {
state.films = films;
},
setFilm: (state, film) => {
state.film = film;
}
};
export const actions = {
async getFilms({ commit }) {
try {
const films = await this.$axios.$get("/api/films");
commit("setFilms", films);
} catch (e) {
throw Error("API Error occurred.");
}
},
async getFilm({ commit }, id) {
try {
const film = await this.$axios.$get(`/api/films/${id}`);
commit("setFilm", film);
} catch (e) {
throw Error("API Error occurred.");
}
}
};
export const getters = {};

35
test/actions.spec.js Normal file
View File

@@ -0,0 +1,35 @@
import { actions, mutations } from "@/store";
import axios from "axios";
import mockFilms from "@/test/fake-films.json";
let url = "";
jest.mock("axios", () => ({
$get: _url => {
return new Promise(resolve => {
url = _url;
resolve(mockFilms);
});
}
}));
describe("Vuex actions.", () => {
it("tests getFilms action.", async () => {
const commit = jest.fn();
actions.$axios = axios;
await actions.getFilms({ commit });
expect(url).toBe("/api/films");
expect(commit).toHaveBeenCalledWith("setFilms", mockFilms);
});
it("catches errors.", async () => {
const commit = jest.fn();
actions.$axios = null;
await expect(actions.getFilms({ commit })).rejects.toThrow(
"API Error occurred."
);
});
});

9
test/mutations.spec.js Normal file
View File

@@ -0,0 +1,9 @@
import { state, mutations } from "@/store";
import mockFilms from "./fake-films.json";
describe("Vuex mutations.", () => {
it("tests setFilms mutation.", () => {
mutations.setFilms(state, mockFilms);
expect(state.films[0].id).toBe(mockFilms[0].id);
});
});