All Questions
Tagged with vitest javascript
173 questions
1
vote
0
answers
56
views
Unit test when there is style on the component
I'm checking out Svelte 5 and I have this simple component
<script lang="ts">
let {
name
}: {
name: string;
} = $props();
</script>
<h1>
...
-2
votes
1
answer
110
views
+100
Code behaves differently in Vitest vs React
I have a simple test case:
import {describe, it, test} from "vitest";
import {decodeBase64, hexlify} from "ethers";
describe('zapModule', () => {
it('smoke test vitest', ...
0
votes
0
answers
58
views
How to test custom hook with useEffect in React 18?
Hook:
import { useEffect, useState } from "react";
const useIsClient = () => {
const [isClient, setIsClient] = useState(false);
useEffect(() => {
setIsClient(true);
}, []);
...
-1
votes
2
answers
71
views
Why is function never called in test
I need help regarding a specific test. I have a Component, that is toggling the sound on and off in my project. The last test, with which I try to test if the e.prevenDefault gets called does not work,...
0
votes
0
answers
47
views
Vitest not picking up my mocked environment variables when testing axios call
I've got the following function:
import axios from 'axios'
const apiKey = import.meta.env.VITE_KEY
const apiURL = import.meta.env.VITE_URL
const headers = {
'key': apiKey,
'host': apiURL.replace(...
0
votes
0
answers
39
views
How to mock class implementation used in a another class using vitest
Assume I have 2 modules that defines Repo and Service classes.
// src/Repo.ts
export class Repo {
find() {
return "hello";
}
}
// src/Service.ts
import { Repo } from "./Repo&...
-1
votes
2
answers
63
views
Why should I mock a function instead of using the function itself to unit test?
I'm honestly confused about the goal of mocking certain functions when unit testing my app. I've seen articles suggesting I should mock everything I test, but also others suggesting I should avoid ...
0
votes
0
answers
24
views
SpyOn function does not recognize call after click event
I want to write a unit test for the function renderSetupPage with Vitest. Somthing with the mocked function startGame seems to be wrong, but I can't find the error.
../scripts/utils.js:
export const ...
1
vote
1
answer
766
views
Deprecation Warning: The legacy JS API is deprecated and will be removed in Dart Sass 2.0.0. at run vitest
vitest.config.js:
import { defineConfig, mergeConfig } from 'vitest/config'
import viteConfig from './vite.config'
export default mergeConfig(
viteConfig,
defineConfig({
test: {
...
0
votes
0
answers
54
views
How to mock class implementation in vitest
We have existing code that's structured similar to following which I want to test. The challenging part here is the fact that instance of Two is created at module root level in Three.ts file. This ...
0
votes
0
answers
17
views
vitest -- vue creates the component, function needs data produced by a different function
I am attempting to write integration tests for an existing application. The component I am testing loads the preference of the user by account and displays them so the user can change them if he ...
1
vote
1
answer
597
views
How to make vitest fail fast after first known test failure
I am using Vitest for testing and would like it to fail fast upon first error. The reason is that I'm using it within git bisect and don't need to waste time on the whole test run once there is an ...
0
votes
0
answers
117
views
Vite path aliases in imported submodule
I have a project, let's call it parent, which depends on a submodule sub.
parent/
│ vite.config.js
│ package.json
│ src/
│ ...
│
└───sub/
│ vite.config.js
│ package.json
│ src/
│ │ ...
0
votes
1
answer
56
views
Why is this Vitest test for a thunk returning incorrectly?
When a player is 1 or 2 spaces away from an npc, the npc moves away by 1 through a dispatched thunk.
This works well in my project but I'm struggling to replicate it in my tests. I'm probably missing ...
0
votes
2
answers
459
views
VueJs + vitest how to access functions in the component in test?
I'm in a situation where I don't know how to test a VueJS component, I think essentially because both vue and vitest are new to me, but I cannot find any solution googling around.
I have one component ...
0
votes
1
answer
236
views
Type error in TypeScript 5.6: Type '() => Generator<string, void, any>' is not assignable to type '() => BuiltinIterator<string, undefined, any>'
For my unit tests I create a fake window.location object. Here's the slightly simplified code:
function getFakeLocation(getCurrentUrl: () => URL): Location {
return {
get ancestorOrigins(): ...
0
votes
0
answers
34
views
Mocking function from tested file is not working
I am trying to mock a function from a file which I try to test with Vitest.
test.ts:
export const bar = () => 'bar'
export const foo = () => `I am foo. bar is ${bar()}`
test.unit.spec.ts:
...
0
votes
1
answer
110
views
Got error "Function called outside component initialization" when testing Svelte component with Vitest
I want to test the following Svelte component with Vitest:
<script context="module">
import {push} from 'svelte-spa-router'
import {onDestroy} from 'svelte'
let time = ...
0
votes
0
answers
16
views
Testing a method in a Vue3 setup component with vitest [duplicate]
I need to make a test for a method in a VUE3 setup in a component and nothing I have tried works.
Here is the simplified component:
<script setup>
function myFunction(number) {
return number ...
1
vote
1
answer
130
views
How to spy on Vue composable inner function that is called inside another function inside composable?
The project is using Vue, Vitest and Vue Test Utils. I am new to UI unit testing and I need to test that when one function from composable is called, then the other function should have been called.
...
1
vote
1
answer
187
views
Vue 3 and Vitest focus input sets document.activeElement to HTMLBodyElement in test in composition API
Given a Vue 3 component
<template>
<input id="input" type="text" @focus="handleOnFocus($event)" />
</template>
<script setup type="ts">...
3
votes
2
answers
1k
views
How to ignore lines of code from coverage in vitest?
I have my unit tests setup with vitest and I am looking for a way to ignore specific lines of code from vitest coverage.
Looking for something similar to /* istanbul ignore next */.
Is there something ...
0
votes
2
answers
221
views
supertest request body is undefined
I want to test my express server POST endpoint using supertest. Everything works fine in postman, but when I try to pass in body parameters into the test, as can be seen in the code snippets below, it ...
2
votes
1
answer
299
views
useLoaderData must be used in a data router - Vitest - npm run test
In attempting to test React components that implement the React Router API, I'm getting an error while running tests at the same time. If either test is commented out the error is not raised and the ...
1
vote
0
answers
233
views
Vitest "SyntaxError: Invalid or unexpected token". Fonts files mocking
In my project I switch from jest tests to Vitest, and a problem has arisen: files with fonts and icons are not being mocking when I want to make a snapshot of component.
Before that, I processed them ...
0
votes
1
answer
66
views
Number.toLocaleString in pt-BR fails in vitest
I've defined a function toCurrency to convert string or number to locale strings:
function toCurrency(
value: string | number,
locale: string = "pt-BR",
currency: string = "...
2
votes
1
answer
63
views
Is it possible that JavaScript setTimeout() fires earlier?
I wrote a utility function to create an async timeout:
export function asyncTimeout(timeout: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, timeout))
}
I also ...
0
votes
0
answers
32
views
Removing [stdin] keypress listener (or going around) from 3rd party app within plugin/extension (Vitest in this case)
I am writing Vitest reporter, when running tests in watch mode there is an active listener on keypress event on stdin. I want to have my own handling of user interaction, and this one pretty ...
0
votes
1
answer
100
views
Mocking the window object causes error Cannot read properties of null (reading '_history') at Window.get history [as history]
I have a Vue component with the following method that I am trying to unit test:
const close = () => {
(window.open('', '_self').opener=window).close()
}
My test looks like this:
import { ...
0
votes
0
answers
215
views
Timeout during backend unit testing with Vitest
Here the code of my method which is used in the repository which I cover with unit tests.
private async getOrderDataForId(
orderData: any,
splitOrders: any,
responseOrders: any,...
0
votes
0
answers
62
views
Vitest giving syntaxerror
I am using vitest to run my ReactComponent tests.
import { render, screen } from '@testing-library/react';
import { Calc } from '../features/explore/Calc';
describe('calc tests', () => {
it('...
4
votes
1
answer
2k
views
TypeError: Cannot read properties of undefined (reading 'test') - Vitest
Upon trying to setting up a test with vitest and running npm run test, an error is being raised with test():
TypeError: Cannot read properties of undefined (reading 'test')
When the explicit import ...
0
votes
0
answers
110
views
Vitest for date-fns function (fromUnixTime) keeps failing
I'm using date-fns, a JavaScript date utility library. I'm trying to write a Vitest for fromUnixTime.
My Vitest keeps failing:
describe("fromUnixTime function", () => {
test("...
0
votes
0
answers
137
views
Vitest how to mock callback?
I have the function inside my VUE 3 composition api file;
`const confirmAndLogin = () => {
AuthServices.getConfirmationCode(
email,
(bindData: IAuthenticationCallback) => {
data =...
0
votes
0
answers
38
views
AssertionError: expected +0 to be 3; vi.spyOn()
In attempting to record the number of mock calls of Math.floor() within the function set_rgb_color, the following error is raised:
AssertionError: expected +0 to be 3 // Object.is equality
- Expected
...
1
vote
0
answers
159
views
Transforming image in Vitest in Next.js codebase
Jest has a way to (not) process imported assets (.jpg, .png, ...) by setting what should be the resolved value. So it can be a mock object:
jest.config.js
module.exports = {
transform: {
'\\.(...
1
vote
1
answer
675
views
Difference between "pnpm run test" and "vitest run"?
I'm new to javascript and now trying to run solid.js source code locally.
I started with the test part.
cd to packages\solid folder https://github.com/solidjs/solid/tree/main/packages/solid
In this ...
0
votes
1
answer
81
views
How can I test a function that is inside a custom hook to work as it is expected?
I have a custom hook that I want to test (I'm using vitest for testing)..
Here is the custom hook.
export const useRerunCustomQuery = (attributes) => {
const {id, staticCustomId, featureSelection}...
0
votes
1
answer
79
views
Why Vue's vue-test-utils test unit does not reach the proper route when using clicking a button?
I'm trying to write test for a form submission and no matter what I tried it failed.
I was able to reduce the problem to a and App (App.vue), 2 components (TroubledLogin.vue and Info.vue) and a test ...
-1
votes
1
answer
551
views
Test mocked try and catch with Vitest in same file
I'm mocking an external library (public-ip). I would test my implementation - I'm using Vitest as test runner:
const getPublicIp = async (): Promise<string> => {
try {
return await ...
2
votes
1
answer
584
views
`Cannot use 'in' operator to search for '_leaflet_id' in null` in testing
I am implementing an integration test with Vitest 1.4.0 and testing-library/react 14.2.1 which renders the main app component. Simply by calling the testing-library render() function, I get this error:...
0
votes
0
answers
295
views
ViTest Axios mock interceptors issue
I am trying to add tests for an axios interceptor that refreshes the token on a failed attempt and retries once with a new token. All tests pass apart from the one I described as: 'should refresh the ...
0
votes
0
answers
486
views
How does Next.js - Vitest testing work with pages that have imported components? All my tests are failing
I have looked at the basic Next.js testing with Vitest documentation here:
https://nextjs.org/docs/app/building-your-application/testing/vitest
And have successfully tested different situations. ...
0
votes
0
answers
255
views
How can I mock API / Module and test this svelte Component
Within my src/lib/apis directory I have a file named data.ts which contains the below code:
export async function getData(searchInput: string) {
return fetch('https://dummyjson.com/products', { ...
0
votes
0
answers
355
views
Vitest, callback not being called
I am trying to test a function that uses a callback.
It looks something like this:
export const foo = (data, callback) => {
response = await callback();
// based on response and data return ...
-1
votes
1
answer
812
views
How do I test routes made with the app router in NextJS? I'm using vitest for this
I´m trying to test routes with vitest on next js 14.1.0. Is this possible? i don´t find any information about that.
i´m expecting some ideas to implement these tests on my project just like i did with ...
1
vote
1
answer
976
views
Vitest: Mocking composable inside of component test
I'm having a difficult time mocking a composable inside of a component.
Looking to see if a function from the composable was called after a button was clicked.
The composable is quite simple:
export ...
0
votes
1
answer
728
views
vitest react write-excel-file: how to test FileSaver.saveAs (download file)
live testsetup for this question:
https://codesandbox.io/p/github/s-light/codesandbox__vitest_write-excel-file
i try to write a test for my react component that displays a button, and when clicked ...
1
vote
0
answers
410
views
Triggering `visibilitychange` event in test (vitest)
In my code, I set an eventListener for visibilitychange, and when running the code in the browser, everything works as intended. I'm trying to replicate the behavior in unit test, and am unable to do ...
-1
votes
1
answer
852
views
Vitest React Redux - expected "spy" to be called with arguments
i getting error like this when I want to test my React application which uses Redux, I want to test the thunk function register
AssertionError: expected "spy" to be called with arguments: [ [...