Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: mock nuxt fetchState in mounter #2471

Merged
merged 3 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/portal/src/components/generic/AlertMessage.vue
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
},
props: {
error: {
type: [String, Object],
type: [String, Object, Error],
default: ''
}
}
Expand Down
1 change: 0 additions & 1 deletion packages/portal/src/pages/feature-ideas/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@
name: null,
description: null,
socialMediaImage: null,
pageFetched: false,
text: null,
features: []
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,6 @@ const factory = (propsData = { sectionType: FEATURED_TOPICS }) => shallowMountN
$contentful: {
query: sinon.stub()
},
$fetchState: {
error: false,
pending: false
},
localePath: () => 'mocked path',
$i18n: { locale: 'en', t: (key) => key, n: (num) => `${num}`, localeProperties: { iso: 'en-GB' } },
$route: { query: {} },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@ const fixtures = {

const factory = (propsData = {}) => shallowMountNuxt(EmbedHTML, {
propsData,
localVue,
mocks: {
$fetchState: {}
}
localVue
});

describe('components/embed/EmbedHTML', () => {
Expand Down
15 changes: 5 additions & 10 deletions packages/portal/tests/unit/components/embed/EmbedOEmbed.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,9 @@ const factory = ({ propsData = {}, data = {} } = {}) => shallowMountNuxt(EmbedOE
}),
localVue,
mocks: {
$fetchState: {},
$t: (key) => key
},
stubs: ['EmbedHTML', 'client-only']
stubs: ['EmbedHTML', 'client-only', 'AlertMessage']
});

describe('components/embed/EmbedOEmbed', () => {
Expand Down Expand Up @@ -74,21 +73,17 @@ describe('components/embed/EmbedOEmbed', () => {
expect(wrapper.vm.providerName).toBe(response['provider_name']);
});

it('throws an error if response does not contain HTML', async() => {
it('displays an error if response does not contain HTML', async() => {
const response = {
type: 'link'
};
const wrapper = factory({ propsData: { url, endpoint } });
nockRequest().reply(200, response);

let error;
try {
await wrapper.vm.fetch();
} catch (e) {
error = e;
}
await wrapper.vm.fetch();
const alertMessage = wrapper.find('alertmessage-stub');

expect(error.message).toBe('messages.externalContentError');
expect(alertMessage.attributes('error')).toContain('messages.externalContentError');
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ const factory = ({ propsData = {}, data = {}, responses } = {}) => {
$apis: {
record: { search: sinon.stub().resolves(responses?.record?.search || {}) }
},
$fetchState: {},
$store: {
state: {
search: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,10 @@ localVue.use(BootstrapVue);

const $axiosGetStub = sinon.stub();

const factory = (propsData = { type: 'organisations' }, fetchState = { error: false, pending: false }) => mountNuxt(EntityTable, {
const factory = (propsData = { type: 'organisations' }) => mountNuxt(EntityTable, {
localVue,
propsData,
mocks: {
$fetchState: fetchState,
$axios: {
get: $axiosGetStub
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ const factory = ({ propsData = {}, mocks = {} } = {}) => {
},
$config: config,
$error: sinon.spy(),
$fetchState: {},
$nuxt: { context: {} },
$t: (key) => key,
$tc: (key) => key,
Expand Down
3 changes: 1 addition & 2 deletions packages/portal/tests/unit/components/home/HomePage.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ const factory = ({ data = {} } = {}) => shallowMountNuxt(HomePage, {
$t: (key) => key,
localePath: (args) => {
return args.params ? `${args.params.type}/${args.params.pathMatch}` : args;
},
$fetchState: {}
}
},
stubs: ['b-container']
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ const factory = ({ data = {}, propsData = {}, mocks = {} } = {}) => shallowMount
},
mocks: {
$apis,
$fetchState: { pending: false },
$nuxt: {
context: {
$apis
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ const factory = ({ propsData = {}, mocks = {} } = {}) => shallowMountNuxt(ItemRe
}
},
$auth: {},
$fetchState: {},
$i18n: { locale: 'en' },
$t: key => key,
...mocks
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ const factory = ({ mocks = {} } = {}) => shallowMountNuxt(ItemTrendingItems, {
}
},
$features: { mockTrendingItems: false },
$fetchState: {},
...mocks
},
stubs: ['b-container']
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ const factory = ({ data, propsData, mocks } = {}) => shallowMountNuxt(MediaAnnot
annotationScrollToContainerSelector: '#list-container'
},
mocks: {
$fetchState: {},
$route: {
query: {}
},
Expand All @@ -38,7 +37,7 @@ const factory = ({ data, propsData, mocks } = {}) => shallowMountNuxt(MediaAnnot
...mocks
},
localVue,
stubs: ['NuxtLink']
stubs: ['NuxtLink', 'b-col', 'b-row', 'b-container']
});

const stubItemMediaPresentationComposable = (stubs = {}) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ const factory = ({ propsData = {}, mocks = {} } = {}) => shallowMountNuxt(MediaI
mediaProxyUrl: (url) => `mediaProxyUrl ${url}`
}
},
$fetchState: {},
$t: (key) => key,
...mocks
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ const factory = (options = {}) => {
propsData: options.propsData,
mocks: {
$apis: { entity: { suggest: sinon.stub().resolves(relatedCollections) } },
$fetchState: {},
$i18n: { locale: 'en' },
$t: key => key,
$store: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,6 @@ const factory = (options = {}) => shallowMountNuxt(SearchFacetDropdown, {
search: apisRecordSearchStub
}
},
$fetchState: options.fetchState || {},
$route: {
query: {}
},
Expand All @@ -108,7 +107,8 @@ const factory = (options = {}) => shallowMountNuxt(SearchFacetDropdown, {
state: {
search: {}
}
}
},
...options.mocks || {}
},
stubs: {
'b-form-tags': {
Expand All @@ -131,7 +131,6 @@ const fullFactory = (options = {}) => mountNuxt(SearchFacetDropdown, {
search: apisRecordSearchStub
}
},
$fetchState: options.fetchState || {},
$route: {
query: {}
},
Expand All @@ -150,7 +149,8 @@ const fullFactory = (options = {}) => mountNuxt(SearchFacetDropdown, {
state: {
search: {}
}
}
},
...options.mocks || {}
},
stubs: ['i18n'],
propsData: {
Expand Down Expand Up @@ -857,9 +857,6 @@ describe('components/search/SearchFacetDropdown', () => {
propsData: {
search: true,
name: 'PROVIDER'
},
fetchState: {
pending: false
}
});
await wrapper.setData({ fetched: true, fields: providerFields });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,13 @@ const searchResult = {

const logApmTransactionSpy = sinon.spy();

const factory = ({ $fetchState = {}, mocks = {}, propsData = {}, data = {} } = {}) => shallowMountNuxt(SearchInterface, {
const factory = ({ mocks = {}, propsData = {}, data = {} } = {}) => shallowMountNuxt(SearchInterface, {
localVue,
attachTo: document.body,
mocks: {
$t: (key) => key,
localePath: () => '/',
$router: { push: sinon.spy() },
$fetchState,
$route: { path: '/search', name: 'search', query: {} },
$error: sinon.spy(),
localise: (val) => val,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ const factory = ({ propsData = {}, features = {}, recommendations = [] }) => sha
mocks: {
$apis: { recommendation: { recommend: sinon.stub().resolves({ items: recommendations }) } },
$features: features,
$fetchState: {},
$store: {
commit: sinon.spy(),
state: { set: { activeRecommendations: recommendations } }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ const contentfulQueryStub = () => {
return stub;
};

const factory = ({ data = {}, propsData = {}, $fetchState = {}, mocks = {} } = {}) => shallowMountNuxt(StoriesInterface, {
const factory = ({ data = {}, propsData = {}, mocks = {} } = {}) => shallowMountNuxt(StoriesInterface, {
localVue,
data() {
return data;
Expand All @@ -159,7 +159,6 @@ const factory = ({ data = {}, propsData = {}, $fetchState = {}, mocks = {} } = {
page: '1'
}
},
$fetchState,
$t: (key) => key,
$tc: (key) => key,
...mocks
Expand All @@ -170,7 +169,7 @@ const factory = ({ data = {}, propsData = {}, $fetchState = {}, mocks = {} } = {
describe('components/stories/StoriesInterface', () => {
describe('while the fetch state is pending', () => {
it('show a loading spinner', async() => {
const wrapper = factory({ $fetchState: { pending: true } });
const wrapper = factory({ mocks: { $fetchState: { pending: true } } });

const spinner = wrapper.find('loadingspinner-stub');

Expand All @@ -180,7 +179,7 @@ describe('components/stories/StoriesInterface', () => {

describe('when the fetch state is complete', () => {
it('show a loading spinner', async() => {
const wrapper = factory({ $fetchState: { pending: false } });
const wrapper = factory({ mocks: { $fetchState: { pending: false } } });

const spinner = wrapper.find('loadingspinner-stub');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ const factory = ({ propsData = {}, data = {}, $route = {} } = {}) => shallowMoun
mocks: {
$auth: { user: { sub: 'user-id' } },
$config: { app: { internalLinkDomain: null } },
$fetchState: {},
$apis: {
set: { search: sinon.stub().resolves({ items: sets, partOf: { total: sets.length } }) },
thumbnail: { edmPreview: (img) => img?.edmPreview?.[0] }
Expand Down
9 changes: 5 additions & 4 deletions packages/portal/tests/unit/pages/feature-ideas/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,17 @@ const contentfulFullResponse = { data: { data: { featureIdeasPageCollection: { i
] }
}] } } } };

const factory = ({ contentfulResponse = {}, $fetchState = {} }) => shallowMountNuxt(featureIdeasPage, {
const factory = ({ contentfulResponse = {}, mocks = {} }) => shallowMountNuxt(featureIdeasPage, {
localVue,
mocks: {
$contentful: {
query: sinon.stub().resolves(contentfulResponse)
},
$fetchState,
$i18n: { localeProperties: { iso: 'en-GB' } },
$route: { query: {} },
$t: key => key
$t: (key) => key,
$tc: (key) => key,
...mocks
}
});

Expand All @@ -55,7 +56,7 @@ describe('pages/feature-ideas/index', () => {

describe('when fetch errors', () => {
it('renders an alert message', () => {
const wrapper = factory({ $fetchState: { error: { message: 'Error message' } } });
const wrapper = factory({ mocks: { $fetchState: { error: { message: 'Error message' } } } });

const alertMessage = wrapper.find('[data-qa="alert message container"]');

Expand Down
27 changes: 23 additions & 4 deletions packages/portal/tests/unit/utils.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,44 @@
import { mount, shallowMount } from '@vue/test-utils';
import { ref } from 'vue';
import sinon from 'sinon';

const NUXT_METHODS = [
'asyncData', 'fetch', 'head', 'beforeRouteEnter', 'beforeDestroy', 'watch', 'mounted', 'middleware', 'layout'
'asyncData', 'head', 'beforeRouteEnter', 'beforeDestroy', 'watch', 'mounted', 'middleware', 'layout'
];

const injectNuxtMethods = (wrapper, pageOrComponent) => {
for (const method of NUXT_METHODS) {
wrapper.vm[method] = pageOrComponent[method];
wrapper.vm['$fetch'] = pageOrComponent.fetch;
}

wrapper.vm.fetch = async function() {
try {
wrapper.vm['$fetchState'].pending = true;
await pageOrComponent.fetch.bind(wrapper.vm)();
} catch (e) {
wrapper.vm['$fetchState'].error = e;
} finally {
wrapper.vm['$fetchState'].pending = false;
}
};
wrapper.vm['$fetch'] = wrapper.vm.fetch;

return wrapper;
};

const mountOptionsWithFetchState = (options) => {
options.mocks ||= {};
options.mocks.$fetchState ||= { error: ref(null), pending: ref(false) };
return options;
};

export const shallowMountNuxt = (pageOrComponent, options = {}) => {
const wrapper = shallowMount(pageOrComponent, options);
const wrapper = shallowMount(pageOrComponent, mountOptionsWithFetchState(options));
return injectNuxtMethods(wrapper, pageOrComponent);
};

export const mountNuxt = (pageOrComponent, options = {}) => {
const wrapper = mount(pageOrComponent, options);
const wrapper = mount(pageOrComponent, mountOptionsWithFetchState(options));
return injectNuxtMethods(wrapper, pageOrComponent);
};

Expand Down
Loading