Yuri
Yuri
NNuxt
Created by Yuri on 1/6/2025 in #❓・help
The plugin is executed twice
Hello. I have the plugin (
01.init.ts
01.init.ts
), which generates (or refreshes) a token. But it is executed twice: on the server and on the client. But I need the plugin start only once. If it was executed on the server, it should not be executed on the client. But also I use SPA of this project for mobile app (Capacitor) and I can't to rename plugin to
01.init.server.ts
01.init.server.ts
because in this case the plugin have to start on the client. What are the appropriate options to solve my problem?
4 replies
NNuxt
Created by Yuri on 1/4/2025 in #❓・help
postcss-normalize
Hello. What is the correct way for reset styles in the Nuxt-project using post-normalize?
9 replies
NNuxt
Created by Yuri on 12/27/2024 in #❓・help
JWT generation
Hello. I create an e-commerce project. I want to use JWT (access & refresh) for everybody (guests & users). Also I want to use /server/api. I create plugins/api.ts for custom fetch. I guess to create /server/api/token/get & /server/api/token/refresh/ for working with tokens. My questions: 1. Where do I need first request to token/get for getting the token pair? 2. When the page loads I need to check "Does the cookie refreshToken exist?" If YES I need to fetch /token/refresh/. Where do I need to do it? Maybe is there some ready solution?
6 replies
NNuxt
Created by Yuri on 12/26/2024 in #❓・help
Deprecation Warning: The legacy JS API is deprecated and will be removed in Dart Sass 2.0.0.
Hi. How can I hidden this warning. I use Nuxt & tailwindCSS.
11 replies
NNuxt
Created by Yuri on 12/25/2024 in #❓・help
Testing $fetch
My api.ts utils:
export const apiBack = async <T>(
url: string,
token: string,
options: NitroFetchOptions<string> = {},
): Promise<T> => {
options.baseURL = process.env.BITRIX_API_URL
setAuthorizationHeader(options, token)

const response = await $fetch<T>(url, options)
return response as T
}
export const apiBack = async <T>(
url: string,
token: string,
options: NitroFetchOptions<string> = {},
): Promise<T> => {
options.baseURL = process.env.BITRIX_API_URL
setAuthorizationHeader(options, token)

const response = await $fetch<T>(url, options)
return response as T
}
I write this test:
import { describe, it, expect,} from 'vitest';
import {apiBack} from "~/utils/api";
import {testMockTokenAccess, testMockUrlRelative} from "~/utils/tests";
import { $fetch } from '@nuxt/test-utils'


describe('api Utils',()=>{
it('Проверка корректной работы запросов к беку apiBack',()=>{
apiBack(testMockUrlRelative,testMockTokenAccess)
expect($fetch).toHaveBeenCalled();
})
})
import { describe, it, expect,} from 'vitest';
import {apiBack} from "~/utils/api";
import {testMockTokenAccess, testMockUrlRelative} from "~/utils/tests";
import { $fetch } from '@nuxt/test-utils'


describe('api Utils',()=>{
it('Проверка корректной работы запросов к беку apiBack',()=>{
apiBack(testMockUrlRelative,testMockTokenAccess)
expect($fetch).toHaveBeenCalled();
})
})
And I get the error:
FetchError: [GET] "/catalog": 404 Cannot find any path matching /catalog.
FetchError: [GET] "/catalog": 404 Cannot find any path matching /catalog.
on this line
const response = await $fetch<T>(url, options)
const response = await $fetch<T>(url, options)
What is correct variant to check my apiBack function ?
20 replies
NNuxt
Created by Yuri on 12/15/2024 in #❓・help
"async-component-wrapper-stub" testing
Hello. A part of my component is:
<div
v-if="showSuggestions"
class="absolute -inset-x-8 -top-8 min-h-64 bg-white px-4 pb-8 pt-24 shadow-lg"
:class="classSuggestsWrapper"
>
<LazySearchQuickSuggests
:tips="searchResult?.tips ?? []"
:intro="introStatus"
:products="searchResult?.products ?? []"
:categories="searchResult?.categories ?? []"
:suggests="searchResult?.suggests ?? []"
:brands="searchResult?.brands ?? []"
@select-tip="selectTip($event)"
/>
<LazyAppLoading v-if="isLoadingSuggests" />
</div>
<div
v-if="showSuggestions"
class="absolute -inset-x-8 -top-8 min-h-64 bg-white px-4 pb-8 pt-24 shadow-lg"
:class="classSuggestsWrapper"
>
<LazySearchQuickSuggests
:tips="searchResult?.tips ?? []"
:intro="introStatus"
:products="searchResult?.products ?? []"
:categories="searchResult?.categories ?? []"
:suggests="searchResult?.suggests ?? []"
:brands="searchResult?.brands ?? []"
@select-tip="selectTip($event)"
/>
<LazyAppLoading v-if="isLoadingSuggests" />
</div>
And a part of my test:
it('Клик по полю ввода вызывает handleInputFocus', async () => {
const wrapper = shallowMount(SearchQuick);
const input = wrapper.find(SearchQuick__input);
let SearchQuickSuggestsComponent = wrapper.findComponent(SearchQuickSuggestsSuggests);
expect(SearchQuickSuggestsComponent.exists()).toBe(false);
await input.trigger('focus');
await flushPromises();
console.log(wrapper.html());
SearchQuickSuggestsComponent = wrapper.findComponent(SearchQuickSuggestsSuggests);
expect(SearchQuickSuggestsComponent.exists()).toBe(true);
});
it('Клик по полю ввода вызывает handleInputFocus', async () => {
const wrapper = shallowMount(SearchQuick);
const input = wrapper.find(SearchQuick__input);
let SearchQuickSuggestsComponent = wrapper.findComponent(SearchQuickSuggestsSuggests);
expect(SearchQuickSuggestsComponent.exists()).toBe(false);
await input.trigger('focus');
await flushPromises();
console.log(wrapper.html());
SearchQuickSuggestsComponent = wrapper.findComponent(SearchQuickSuggestsSuggests);
expect(SearchQuickSuggestsComponent.exists()).toBe(true);
});
console.log show
<async-component-wrapper-stub tips="Tip 1,Tip 2" intro="true" products="" categories="" suggests="" brands=""></async-component-wrapper-stub>
<async-component-wrapper-stub tips="Tip 1,Tip 2" intro="true" products="" categories="" suggests="" brands=""></async-component-wrapper-stub>
But test is not success:
expect(SearchQuickSuggestsComponent.exists()).toBe(true);
expect(SearchQuickSuggestsComponent.exists()).toBe(true);
How can I improve the test to get it to pass?
6 replies
NNuxt
Created by Yuri on 12/14/2024 in #❓・help
The test ignores useNuxtApp
Hello, everyone! I need help with unit-testing. My component LocationSelection.vue:
<template>
<div>{{test}}</div>
</template>

<script lang="ts" setup>
const test = ref('111')
const fetchCities = async () => {
test.value = '222';
const nuxtApp = useNuxtApp()
await nuxtApp.$api(apiPath.location.suggest.city)
test.value = '333';
}

onMounted(async () => {
await fetchCities()
})
</script>
<template>
<div>{{test}}</div>
</template>

<script lang="ts" setup>
const test = ref('111')
const fetchCities = async () => {
test.value = '222';
const nuxtApp = useNuxtApp()
await nuxtApp.$api(apiPath.location.suggest.city)
test.value = '333';
}

onMounted(async () => {
await fetchCities()
})
</script>
My LocationSelection.nuxt.spec.ts:
import { describe, it, expect } from 'vitest'
import { mountSuspended } from '@nuxt/test-utils/runtime'
import LocationSelection from '../LocationSelection.vue'

describe('LocationSelection.vue', () => {
it('test', async () => {
const wrapper = await mountSuspended(LocationSelection)
await wrapper.vm.$nextTick()
console.log(wrapper.html())
expect(wrapper.text()).toContain('333')
})
})
import { describe, it, expect } from 'vitest'
import { mountSuspended } from '@nuxt/test-utils/runtime'
import LocationSelection from '../LocationSelection.vue'

describe('LocationSelection.vue', () => {
it('test', async () => {
const wrapper = await mountSuspended(LocationSelection)
await wrapper.vm.$nextTick()
console.log(wrapper.html())
expect(wrapper.text()).toContain('333')
})
})
But why do I receive 222 instead 333?
AssertionError: expected '222' to contain '333'
AssertionError: expected '222' to contain '333'
13 replies
NNuxt
Created by Yuri on 12/13/2024 in #❓・help
useNuxtApp && mountSuspended
My Component:
<template>
<div>{{test}}</div>
</template>

<script lang="ts" setup>
const test = ref('111')
const fetchCities = async () => {
test.value = '222';
const nuxtApp = useNuxtApp()
await nuxtApp.$api(apiPath.location.suggest.city)
test.value = '333';
}

onMounted(async () => {
await fetchCities()
})
</script>
<template>
<div>{{test}}</div>
</template>

<script lang="ts" setup>
const test = ref('111')
const fetchCities = async () => {
test.value = '222';
const nuxtApp = useNuxtApp()
await nuxtApp.$api(apiPath.location.suggest.city)
test.value = '333';
}

onMounted(async () => {
await fetchCities()
})
</script>
My test:
import { describe, it, vi } from 'vitest'
import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime'
import LocationSelection from '../LocationSelection.vue'
import {flushPromises} from "@vue/test-utils";

describe('LocationSelection.vue', () => {
const createWrapper = async () => {
return await mountSuspended(LocationSelection)
}

it('test',async ()=>{
const wrapper = await createWrapper();
await flushPromises();
await wrapper.vm.$nextTick();
console.log(wrapper.html());
})
})
import { describe, it, vi } from 'vitest'
import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime'
import LocationSelection from '../LocationSelection.vue'
import {flushPromises} from "@vue/test-utils";

describe('LocationSelection.vue', () => {
const createWrapper = async () => {
return await mountSuspended(LocationSelection)
}

it('test',async ()=>{
const wrapper = await createWrapper();
await flushPromises();
await wrapper.vm.$nextTick();
console.log(wrapper.html());
})
})
Why console.log render
<div>222</div>
<div>222</div>
Why not "333" ? How can I fix this error?
10 replies
NNuxt
Created by Yuri on 12/13/2024 in #❓・help
Unit Test OnMounted
My component:
import { debounce, upperCase } from 'lodash'
import type { ILocationCitySuggestItem, ILocationCitySuggests } from '~/types/location'
import { useLocationStore } from '~/store/location'

const locationStore = useLocationStore()
const customCSS = useCustomCSS()

// Состояние поиска и списков городов
const searchText = ref('')
const cities: Ref<ILocationCitySuggestItem[]> = ref([])
const initialCities: Ref<ILocationCitySuggestItem[]> = ref([]) // Исходный список городов
const isLoading = ref(false)

// Функция для получения списка городов
const fetchCities = async (query: string | null = null) => {
isLoading.value = true
const nuxtApp = useNuxtApp()
const params = query ? { query: upperCase(query) } : {}

const response = await nuxtApp.$api<ILocationCitySuggests>(apiPath.location.suggest.city, { params })
cities.value = response.items
isLoading.value = false
}

// Дебаунс-функция для оптимизации запросов
const debouncedFetchCities = debounce(() => fetchCities(searchText.value), 300)

// Обновление списка городов при изменении `searchText`
watch(searchText, (newVal) => {
if (newVal) {
debouncedFetchCities()
}
else {
cities.value = initialCities.value
}
})

// Инициализация компонента и начальная загрузка городов
onMounted(async () => {
await fetchCities()
initialCities.value = cities.value
})

// Выбор города
const selectLocation = async (id: number) => {
await locationStore.updateCurrent(id)
}
import { debounce, upperCase } from 'lodash'
import type { ILocationCitySuggestItem, ILocationCitySuggests } from '~/types/location'
import { useLocationStore } from '~/store/location'

const locationStore = useLocationStore()
const customCSS = useCustomCSS()

// Состояние поиска и списков городов
const searchText = ref('')
const cities: Ref<ILocationCitySuggestItem[]> = ref([])
const initialCities: Ref<ILocationCitySuggestItem[]> = ref([]) // Исходный список городов
const isLoading = ref(false)

// Функция для получения списка городов
const fetchCities = async (query: string | null = null) => {
isLoading.value = true
const nuxtApp = useNuxtApp()
const params = query ? { query: upperCase(query) } : {}

const response = await nuxtApp.$api<ILocationCitySuggests>(apiPath.location.suggest.city, { params })
cities.value = response.items
isLoading.value = false
}

// Дебаунс-функция для оптимизации запросов
const debouncedFetchCities = debounce(() => fetchCities(searchText.value), 300)

// Обновление списка городов при изменении `searchText`
watch(searchText, (newVal) => {
if (newVal) {
debouncedFetchCities()
}
else {
cities.value = initialCities.value
}
})

// Инициализация компонента и начальная загрузка городов
onMounted(async () => {
await fetchCities()
initialCities.value = cities.value
})

// Выбор города
const selectLocation = async (id: number) => {
await locationStore.updateCurrent(id)
}
How can I check that fetchCities has been called on mounted hook and initialCities was been set ? I use @nuxt/test-utils
29 replies
NNuxt
Created by Yuri on 12/13/2024 in #❓・help
Change URL in unit-test with useRoute
import {describe, it, expect,} from 'vitest';
import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime';
import LayoutLogo from '../LayoutLogo.vue';
import {useLayoutStore} from "~/store/layout";
import {NuxtLink} from "#components";

// Mock useRoute and useLayoutStore
mockNuxtImport('useRoute', () => {
return () => ({
fullPath: '/' // default mock path
});
});

const initialLogo = {
width: 100,
height: 50,
alt: '',
src:"https://example.com/test-image.jpg",
}
describe('LayoutLogo.vue', () => {
const createWrapper = async () => {
const layoutStore = useLayoutStore();
layoutStore.logo = initialLogo
return await mountSuspended(LayoutLogo);
};

it('Рендер корректного компонента в зависимости от страницы', async () => {
const wrapper = await createWrapper();
expect(wrapper.find('> div').exists()).toBe(true);

// HOW CHANGE URL ?
const wrapper2 = await createWrapper();
expect(wrapper2.findComponent(NuxtLink).exists()).toBe(true);
expect(wrapper2.find('div').exists()).toBe(false);
});
});
import {describe, it, expect,} from 'vitest';
import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime';
import LayoutLogo from '../LayoutLogo.vue';
import {useLayoutStore} from "~/store/layout";
import {NuxtLink} from "#components";

// Mock useRoute and useLayoutStore
mockNuxtImport('useRoute', () => {
return () => ({
fullPath: '/' // default mock path
});
});

const initialLogo = {
width: 100,
height: 50,
alt: '',
src:"https://example.com/test-image.jpg",
}
describe('LayoutLogo.vue', () => {
const createWrapper = async () => {
const layoutStore = useLayoutStore();
layoutStore.logo = initialLogo
return await mountSuspended(LayoutLogo);
};

it('Рендер корректного компонента в зависимости от страницы', async () => {
const wrapper = await createWrapper();
expect(wrapper.find('> div').exists()).toBe(true);

// HOW CHANGE URL ?
const wrapper2 = await createWrapper();
expect(wrapper2.findComponent(NuxtLink).exists()).toBe(true);
expect(wrapper2.find('div').exists()).toBe(false);
});
});
I need to change the URL to another, for example '/catalog/', before rending wrapper2. How can I do it?
5 replies
NNuxt
Created by Yuri on 12/13/2024 in #❓・help
useRoute and mountSuspended - test is freezing
My test:
import { describe, it, expect, } from 'vitest';
import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime';
import { flushPromises } from '@vue/test-utils';
import LayoutLogo from '../LayoutLogo.vue';
import {useLayoutStore} from "~/store/layout";

// Mock useRoute and useLayoutStore
mockNuxtImport('useRoute', () => {
return () => ({
fullPath: '/' // default mock path
});
});

const initialLogo = {
width: 100,
height: 50,
alt: '',
src:"https://example.com/test-image.jpg",
}
describe('LayoutLogo.vue', () => {
const createWrapper = async () => {
const layoutStore = useLayoutStore();
layoutStore.logo = initialLogo
return await mountSuspended(LayoutLogo);
};

it('renders the correct component based on the route', async () => {
const wrapper = await createWrapper();
expect(wrapper.find('div').exists()).toBe(true);
});
});
import { describe, it, expect, } from 'vitest';
import { mockNuxtImport, mountSuspended } from '@nuxt/test-utils/runtime';
import { flushPromises } from '@vue/test-utils';
import LayoutLogo from '../LayoutLogo.vue';
import {useLayoutStore} from "~/store/layout";

// Mock useRoute and useLayoutStore
mockNuxtImport('useRoute', () => {
return () => ({
fullPath: '/' // default mock path
});
});

const initialLogo = {
width: 100,
height: 50,
alt: '',
src:"https://example.com/test-image.jpg",
}
describe('LayoutLogo.vue', () => {
const createWrapper = async () => {
const layoutStore = useLayoutStore();
layoutStore.logo = initialLogo
return await mountSuspended(LayoutLogo);
};

it('renders the correct component based on the route', async () => {
const wrapper = await createWrapper();
expect(wrapper.find('div').exists()).toBe(true);
});
});
My component:
import { useRoute } from 'nuxt/app'
import { NuxtLink } from '#components'
import { useLayoutStore } from '~/store/layout'

const layoutStore = useLayoutStore()
const route = useRoute()

const componentName = computed(() => {
if (route.fullPath === '/') {
return 'div'
}
return NuxtLink
})

const url = computed(() => {
if (route.fullPath === '/') {
return null
}
return '/'
})
import { useRoute } from 'nuxt/app'
import { NuxtLink } from '#components'
import { useLayoutStore } from '~/store/layout'

const layoutStore = useLayoutStore()
const route = useRoute()

const componentName = computed(() => {
if (route.fullPath === '/') {
return 'div'
}
return NuxtLink
})

const url = computed(() => {
if (route.fullPath === '/') {
return null
}
return '/'
})
When I start test, I get error:
TypeError: 'set' on proxy: trap returned falsish for property 'url'
❯ Proxy.clonedComponent.render node_modules/@nuxt/test-utils/dist/runtime-utils/index.mjs:141:44
140| renderContext[key] = methods[key].bind(renderContext);
141| }
142| }
| ^
143| if (computed && typeof computed === "object") {
144| for (const key in computed) {
TypeError: 'set' on proxy: trap returned falsish for property 'url'
❯ Proxy.clonedComponent.render node_modules/@nuxt/test-utils/dist/runtime-utils/index.mjs:141:44
140| renderContext[key] = methods[key].bind(renderContext);
141| }
142| }
| ^
143| if (computed && typeof computed === "object") {
144| for (const key in computed) {
Why?
6 replies
NNuxt
Created by Yuri on 12/11/2024 in #❓・help
mountSuspended & useCookie
Hello. Why my test show incorrect value for cookie? Log: Mock useCookie with value 0 Mock useCookie with value 1 locationConfirmationIsHidden (there isn't cookie): 1 locationConfirmationIsHidden (there is cookie): 1 Part of my component:
const locationConfirmationIsHidden = useCookie<number>(
CookieLocationConfirmationpIsHidden,
cookieGenerateOptionsClient(60 * 60 * 24 * 30, () => 0),
)
await useAsyncData('layoutGetCurrent', () => locationStore.getCurrent())
const locationConfirmationIsHidden = useCookie<number>(
CookieLocationConfirmationpIsHidden,
cookieGenerateOptionsClient(60 * 60 * 24 * 30, () => 0),
)
await useAsyncData('layoutGetCurrent', () => locationStore.getCurrent())
My test:
describe('LayoutHeaderLocation.vue', () => {
const createWrapper = async (initialState = { id: 1, canChange: true, title: 'Астрахань' }) => {
.....
return await mountSuspended(LayoutHeaderLocation);
};

beforeEach(() => {
vi.clearAllMocks();
vi.resetAllMocks();
mockNuxtImport('useCookie', () => () => ({ value: 0 }));
});
it('there isn't cookie', async () => {
mockNuxtImport('useCookie', () => {
console.log('Mock useCookie with value 0');
return () => ({ value: 0 });
});
const wrapper = await createWrapper({ id: 1, canChange: true, title: 'Астрахань' });
await flushPromises();
await wrapper.vm.$nextTick();
console.log('locationConfirmationIsHidden (test куки нет):', wrapper.vm.locationConfirmationIsHidden?.value);
});

it('there is cookie', async () => {
mockNuxtImport('useCookie', () => {
console.log('Mock useCookie with value 1');
return () => ({ value: 1 });
});
const wrapper = await createWrapper({ id: 1, canChange: true, title: 'Астрахань' });
await flushPromises();
await wrapper.vm.$nextTick();
console.log('locationConfirmationIsHidden (there isnt't cookie):', wrapper.vm.locationConfirmationIsHidden?.value);

});
describe('LayoutHeaderLocation.vue', () => {
const createWrapper = async (initialState = { id: 1, canChange: true, title: 'Астрахань' }) => {
.....
return await mountSuspended(LayoutHeaderLocation);
};

beforeEach(() => {
vi.clearAllMocks();
vi.resetAllMocks();
mockNuxtImport('useCookie', () => () => ({ value: 0 }));
});
it('there isn't cookie', async () => {
mockNuxtImport('useCookie', () => {
console.log('Mock useCookie with value 0');
return () => ({ value: 0 });
});
const wrapper = await createWrapper({ id: 1, canChange: true, title: 'Астрахань' });
await flushPromises();
await wrapper.vm.$nextTick();
console.log('locationConfirmationIsHidden (test куки нет):', wrapper.vm.locationConfirmationIsHidden?.value);
});

it('there is cookie', async () => {
mockNuxtImport('useCookie', () => {
console.log('Mock useCookie with value 1');
return () => ({ value: 1 });
});
const wrapper = await createWrapper({ id: 1, canChange: true, title: 'Астрахань' });
await flushPromises();
await wrapper.vm.$nextTick();
console.log('locationConfirmationIsHidden (there isnt't cookie):', wrapper.vm.locationConfirmationIsHidden?.value);

});
5 replies
NNuxt
Created by Yuri on 12/11/2024 in #❓・help
shallowMount & await useAsyncData
Can I use shallowMount instead mountSuspended if my component contain next code:
await useAsyncData('layoutGetCurrent', () => locationStore.getCurrent())
await useAsyncData('layoutGetCurrent', () => locationStore.getCurrent())
With mountSuspended I have a lot of problems.
5 replies
NNuxt
Created by Yuri on 12/10/2024 in #❓・help
[Vue warn]: App already provides property with key "Symbol(pinia)". It will be overwritten with the
Hello. My test:
import { describe, it, expect, vi } from 'vitest'
import { createTestingPinia } from '@pinia/testing'
import { useLocationStore } from '~/store/location'
import LayoutHeaderLocation from '../LayoutHeaderLocation.vue'
import { mockNuxtImport, mountSuspended } from "@nuxt/test-utils/runtime";
import { ref } from 'vue'

mockNuxtImport('useAsyncData', () => {
return () => {
return Promise.resolve({
data: ref(true),
})
}
})

describe('LayoutHeaderLocation.vue', () => {
let locationStore:ReturnType<typeof useLocationStore>
const testingPinia = createTestingPinia({ createSpy: vi.fn })

const createWrapper = async (initialState = { id: 1, canChange: true }) => {
locationStore = useLocationStore()
locationStore.id = initialState.id
locationStore.canChange = initialState.canChange

return await mountSuspended(LayoutHeaderLocation, {
global: { plugins: [testingPinia] },
})
}

it('Рендерится <a> когда canChange=true', async () => {
const wrapper = await createWrapper({ id: 1, canChange: true })
const cityLink = wrapper.find('a')
expect(cityLink.exists()).toBe(true)
expect(cityLink.element.tagName.toLowerCase()).toBe('a')
})
})
import { describe, it, expect, vi } from 'vitest'
import { createTestingPinia } from '@pinia/testing'
import { useLocationStore } from '~/store/location'
import LayoutHeaderLocation from '../LayoutHeaderLocation.vue'
import { mockNuxtImport, mountSuspended } from "@nuxt/test-utils/runtime";
import { ref } from 'vue'

mockNuxtImport('useAsyncData', () => {
return () => {
return Promise.resolve({
data: ref(true),
})
}
})

describe('LayoutHeaderLocation.vue', () => {
let locationStore:ReturnType<typeof useLocationStore>
const testingPinia = createTestingPinia({ createSpy: vi.fn })

const createWrapper = async (initialState = { id: 1, canChange: true }) => {
locationStore = useLocationStore()
locationStore.id = initialState.id
locationStore.canChange = initialState.canChange

return await mountSuspended(LayoutHeaderLocation, {
global: { plugins: [testingPinia] },
})
}

it('Рендерится <a> когда canChange=true', async () => {
const wrapper = await createWrapper({ id: 1, canChange: true })
const cityLink = wrapper.find('a')
expect(cityLink.exists()).toBe(true)
expect(cityLink.element.tagName.toLowerCase()).toBe('a')
})
})
And I get warning:
[Vue warn]: App already provides property with key "Symbol(pinia)". It will be overwritten with the new value.
[Vue warn]: App already provides property with key "Symbol(pinia)". It will be overwritten with the new value.
How can I resolve this?
5 replies
NNuxt
Created by Yuri on 12/9/2024 in #❓・help
useAsyncData & unit-testing
My component contains:
await useAsyncData('layoutGetCurrent', () => locationStore.getCurrent())
await useAsyncData('layoutGetCurrent', () => locationStore.getCurrent())
My test:
import {shallowMount, flushPromises} from '@vue/test-utils'
import {describe, it, vi} from 'vitest'
import { createTestingPinia } from '@pinia/testing'
import LayoutHeaderLocation from '../LayoutHeaderLocation.vue'
import { useLocationStore } from '~/store/location'
import {mockNuxtImport} from "@nuxt/test-utils/runtime";

describe('LayoutHeaderLocation.vue', () => {
mockNuxtImport('useAsyncData', () => {
return () => Promise.resolve({ data: true });
});

const createWrapper = (options = {}) => {
const testingPinia = createTestingPinia({ createSpy: vi.fn })
return shallowMount(LayoutHeaderLocation, {
global: { plugins: [testingPinia] },
...options,
})
}

it('Проверка вызова getCurrent', async () => {
const wrapper = createWrapper()
await flushPromises()
console.log(wrapper.html());
})
})
import {shallowMount, flushPromises} from '@vue/test-utils'
import {describe, it, vi} from 'vitest'
import { createTestingPinia } from '@pinia/testing'
import LayoutHeaderLocation from '../LayoutHeaderLocation.vue'
import { useLocationStore } from '~/store/location'
import {mockNuxtImport} from "@nuxt/test-utils/runtime";

describe('LayoutHeaderLocation.vue', () => {
mockNuxtImport('useAsyncData', () => {
return () => Promise.resolve({ data: true });
});

const createWrapper = (options = {}) => {
const testingPinia = createTestingPinia({ createSpy: vi.fn })
return shallowMount(LayoutHeaderLocation, {
global: { plugins: [testingPinia] },
...options,
})
}

it('Проверка вызова getCurrent', async () => {
const wrapper = createWrapper()
await flushPromises()
console.log(wrapper.html());
})
})
But
console.log(wrapper.html())
console.log(wrapper.html())
does not display anything. If I remove await in component, console.log display render code. Why? How can I resolve this problem?
6 replies
NNuxt
Created by Yuri on 12/8/2024 in #❓・help
Vitest and useCookie
const layoutBannerTopIsHidden = useCookie<boolean>(CookieLayoutBannerTopIsHidden, { maxAge: 60 * 60 * 24 * 7, default: () => false })

if (layoutBannerTopIsHidden.value) {
closeInStore()
}
const layoutBannerTopIsHidden = useCookie<boolean>(CookieLayoutBannerTopIsHidden, { maxAge: 60 * 60 * 24 * 7, default: () => false })

if (layoutBannerTopIsHidden.value) {
closeInStore()
}
How I can mock cookie set ? I want to check two scenarios: 1. CookieLayoutBannerTopIsHidden is TRUE and banner is not showing 2. CookieLayoutBannerTopIsHidden is FALSE and banner not showing
5 replies
NNuxt
Created by Yuri on 11/9/2024 in #❓・help
eslint ignore
My esling.config.mjs:
import tailwind from 'eslint-plugin-tailwindcss'
import { defineFlatConfig } from 'eslint-flat-config-utils'
import withNuxt from './.nuxt/eslint.config.mjs'

export default withNuxt(
defineFlatConfig({
ignores: ['./android/**', './ios/**'],
}),
tailwind.configs['flat/recommended'],
)
import tailwind from 'eslint-plugin-tailwindcss'
import { defineFlatConfig } from 'eslint-flat-config-utils'
import withNuxt from './.nuxt/eslint.config.mjs'

export default withNuxt(
defineFlatConfig({
ignores: ['./android/**', './ios/**'],
}),
tailwind.configs['flat/recommended'],
)
But when I start task lint I receive such error: C:\work\shop**android**\app\build\intermediates\assets\debug\native-bridge.js 4:5 error 'nativeBridge' is assigned a value but never used no-unused-vars How can I exclude android & ios folders from linter?
7 replies
NNuxt
Created by Yuri on 11/3/2024 in #❓・help
Eslint Ignore
I use "@nuxt/eslint": "^0.5.7". What is correct method to add ignore rules to eslint.config.js Now my config is:
import tailwind from 'eslint-plugin-tailwindcss'
import withNuxt from './.nuxt/eslint.config.mjs'

export default withNuxt(
...tailwind.configs['flat/recommended'],
)
import tailwind from 'eslint-plugin-tailwindcss'
import withNuxt from './.nuxt/eslint.config.mjs'

export default withNuxt(
...tailwind.configs['flat/recommended'],
)
I need to add a rule for ignore /android path.
5 replies
NNuxt
Created by Yuri on 10/18/2024 in #❓・help
JWT Example Project
Hello. I develop an online store with Nuxt. I used a third part Backend API before. Now I want to use /server/api for it. And inside /server/API/, requests are sending to the necessary services and the database. I plan to sign all requests with the JWT token and I will keep it in the cookie. Does anyone have examples of such real projects to see how it should be set up correctly?
1 replies
NNuxt
Created by Yuri on 10/3/2024 in #❓・help
Mock API
Hello! What can I use for Mock API. Example: It is my /server/api/contacts/ export default defineCachedEventHandler(async (_event) => { const data = await $fetch('https://example.com/contacts'); return { status: 'success', data, }; }, { maxAge: -1 }); How can I return mock data for 'https://example.com/contacts' (It is example url for back API)
1 replies