Questions tagged [unit-testing]

Unit testing, a critical process in software development, evaluates the suitability and functionality of individual units of source code.

So many private functions in Angular 2! Should we unit test them or perhaps make them public?

It's interesting to note that the majority of functions in my Angular 2 application are private. Take a look at this component, which happens to be my largest one - a form with numerous child components. import { Component, ViewChild, Ele ...

When running the `mocha` command with `npm test`, no specific

Could use some help: I've encountered an issue while running a unit-testing command. The error messages are not being printed when there are errors, making debugging quite challenging. Here is the command I executed: and here's the package.json: cp app/ ...

Transferring token values between collections in POSTMAN - AUTOMATION | NEWMAN: A step-by-step guide

My goal is to streamline my unit test cases by utilizing the POSTMAN Collections API & NEWMAN. I successfully created two test cases that are performing as expected. Upon exporting the collection from POSTMAN, I proceed to generate the test report using NE ...

While running `Django manage.py test`, the `urls.py` file was not visible, even though it is detected

I have a django project structured like this: Base Directory | manage.py | configDir \ | settings.py , urls.py, wsgi.py |mainApp \ |urls.py , views, models etc. | tests \ |urlTest.py (To clarify, there is a django config dire ...

Tips for utilizing the beforeEach feature in node-tap?

Could someone please demonstrate how to utilize the beforeEach function? For more information, visit: . I am particularly interested in seeing an example using promises, although a callback version would also be appreciated. Below is a successfully functi ...

Does the Karma Tast Runner function on node js version 0.12.0?

I'm experiencing an issue where I have Node.js v0.12.0 installed with Karma on my OS X Yosemite, but when I try to run my test task using Gulp, it just hangs as shown in the picture. It seems like PhantomJS is not starting. Interestingly, the same code wor ...

What is the best way to test an AngularJS directive and monitor function calls with a spy?

After running the code below, an error is thrown mentioning that element.popover is not being invoked. I can't seem to identify what the problem is. Thank you in advance for any assistance provided. directive: angular.module('directives', []). directiv ...

How can you provide arguments to a mock function?

While using jest for unit testing, I am encountering the following line of code: jest.mock('../../requestBuilder'); In my project folder, there is a __mocks__ subfolder where I have stored my mock requestBuilder.js file. The jest unit test i ...

Testing the integration of socket.io with Angular through unit tests

Currently, I am in the process of unit testing an angular service within my application that is responsible for creating a socket.io client. The structure of my service can be seen below: export class SocketService { private name: string; private host ...

Issue with running tests in karma-webpack

update: I recently upgraded from karma-webpack 3.0.5 to 4.0.0-rc.2, and encountered some errors. Initially, there was an issue with angular not being defined due to incorrect importing of the home.spec.js file in the tests.bundle.spec. After rectifying thi ...

NYC reporting displays inaccurate line numbers

Our team is currently developing an application utilizing the following front-end stack: VueJS Webpack 2.2 AvaJS (for unit testing) nyc (Istanbul) for test coverage We initially used vue-cli to set up a Webpack template for our project. Everything has b ...

Issue: The Karma plugin in Angular CLI >6.0 is now exported from "@angular-devkit/build-angular" instead

Issue: I'm encountering an error in Angular CLI version 6.0 or higher where the Karma plugin is now exported by "@angular-devkit/build-angular". // Below is the Karma configuration file, you can find more information at // module.exports = function ...

What is the process for importing a server app in Chai for making requests?

I am looking to conduct tests on my node express server, but the way this application starts the server is as follows: createServer() .then(server => { server.listen(PORT); Log.info(`Server started on http://localhost:${PORT}`); }) .catch(err =& ...

Testing the angular components for material chips with input to ensure accurate functionality

I am currently facing an issue while trying to set up a unit test for the mat-chips element. The error message I am encountering is: "Can't bind to 'matChipInputFor' since it isn't a known property of 'input'." It seems that t ...

Steps for generating a unit test for code that invokes scrollIntoView on an HTML element

I'm currently working on an Angular component where I have a method that involves scrolling through a list of elements known as "cards" based on certain criteria. Despite my efforts to write unit tests for this method using the Jasmine framework, I&ap ...

Encountering an undefined error in Angular while running Karma-Jasmine tests

I am struggling with testing using Karma-jasmine to run my tests as I keep encountering errors. Here is a snippet from my karma.conf.js file: files: [ 'test/*Spec.js', 'app/js/*.js' ], When I run the test, I receive the following errors in the comma ...

Unable to modify module variable through monkey patching in Python unit tests

I am currently testing the module: package/module.py DATA_PATH = os.path.join(os.path.dirname(__file__), "data") class SomeClass: def __init__(self): self.filename = os.path.join(DATA_PATH, "ABC.txt") within my tests in module_test.py I have ...

"Creating a mock method in a test file located in a separate directory using Python

Encountering challenges while trying to mock a method, as the mock function is actually overwriting it. In app/tests/test_file.py we currently have the following unit test: @mock.patch('app.method', return_value='foo') def test(self, ...

"Exploring Angular UI-Router by conducting tests with the help of Mocha,

Experimenting with testing the following code in AngularJS using Mocha, Chai, and Sinon. $scope.send = function() { $state.transitionTo('module.sendhome'); }; Here is a test case for validation: it('send' , function () { scope.send(); }); Upon ...

Make sure to log in before running a post request during unit testing with Chai and Mocha

Currently, I am working on testing my post function to only accept data from users with specific permissions. I have successfully implemented a separate login function that is functioning correctly. However, my test code is not recognizing the logged-in us ...

Tips for testing an Angular 6 service with a dependency that utilizes private methods and properties to alter the output of public methods and properties

I've encountered a challenge while attempting to write a Jasmine/Karma test for an Angular 6 app. The test is for a service in my application that relies on another service with private properties and methods, causing my tests to consistently fail. W ...

When setting up Vue.js for unit testing, the default installation may show a message stating that

Recently set up a fresh Vue project on Windows 7 using the VueJS UI utility. Unit testing with Jest enabled and added babel to the mix. However, when running "npm test" in the command line, an error is returned stating 'Error: no test specified' ...

Mastering Mockito for mocking org.openqa.selenium.support.ui.Select components

Unit testing is a vital part of my Selenium integration tests, and in order to effectively test them, I need the ability to mock the selenium Select Object. The method I am testing: protected int findOptionByIgnoreCaseText(String value, Select dropDown) ...

What is the best way to prevent jest.mock from being hoisted and only use it in a single jest unit test?

My goal is to create a mock import that will be used only in one specific jest unit test, but I am encountering some challenges. Below is the mock that I want to be restricted to just one test: jest.mock("@components/components-chat-dialog", () ...

Angular 2 Unit test issue: Unable to resolve parameters for 'RequestOptions' class

I am currently working on testing a simple component that has some dependencies. One of the requirements is to provide certain providers for the test. /* tslint:disable:no-unused-variable */ import { By } from '@angular/platform-browser'; impor ...

AngularJS Error: Attempting to Access Undefined Object - Jasmine Testing

Encountering an error while running Jasmine tests when trying to mock/spy on an API call in the tests. Below is the code snippet responsible for calling the API: UploadedReleasesController.$inject = ['$log', '$scope', '$filter&apo ...

What is the best way to have Vue i18n fetch translations from a .json file during Unit Testing?

Previously, with vue-i18n (v8.25.0 and vue v2.6.14), I stored all translations in .ts files containing JS objects: import { LocaleMessages } from 'vue-i18n' const translations: LocaleMessages = { en: { test: 'Test', }, } export default translatio ...

Not enough test coverage with Jest

Here is the code snippet I am working with: <ReturnToLastSearch href={'/listings'} onClick={(e): void => { e.preventDefault(); router.back(); }} /> The function ReturnToLastSearch( ...

What impact does adding 'ng' in unit tests have on how promises are handled?

Here is an example of a service that utilizes $q.when to wrap a promise from a third-party library: // myService.js angular.module('myApp', []) .service('myService', function($q, $window) { var api = new $window.MyAPI(); this ...

A Python program for testing with Unittest, including input and output file capabilities

I have created a program that consists of one function. This function takes a file as input and writes the result to an output file. I now need to test whether the result matches the expected output. Below is the code for the program: import os def userna ...

Jest is having trouble locating numerous files within the __tests__ directory

I'm facing an issue while trying to use jest with the vue.js framework. When running yarn test:unit (e.g. vue-cli-service test:unit), only the last file in the tests folder is being recognized, even though there are several files present. I have tried ...

Challenges when carrying out unit testing on ZF2 form with CSRF

Unit testing a ZF2 application has presented an interesting challenge. I have a form that adjusts slightly depending on whether it's intended for students or employees, and I've implemented separate factories to generate them. In one of my tests ...

Tips for testing an Angular 2 component that integrates a third-party JavaScript library

Seeking guidance on how to properly test the component below that utilizes a 3rd party JavaScript library - import * as Leaflet from "leaflet"; export class GeoFencingComponent { map: any; constructor() { this.map = Leaflet ...

What is the best method for testing different versions of the same module simultaneously?

My goal is to distribute a module across various component manager systems like npmjs and bower. I also want to provide downloadable builds in different styles such as AMD for requirejs, commonJS, and a global namespace version for browsers - all minified. ...

Testing Angular Components with setInterval FunctionTrying out unit tests in Angular

I'm struggling to figure out how to write unit tests for setInterval in my .component.ts file. Here is the function I have: startTimer() { this.showResend = false; this.otpError = false; this.time = 60; this.interval = setInterval(() => { this.ti ...

Guide to efficiently testing the onChange event for a ui-material TextField component with Jest and Enzyme

I am a beginner in testing and struggling to test the changing value in the TextField component export const ParentComponent = ({ question, onValueChange }: ParentProps) => { const [value, setValue] = useState(default); const on ...

Ways to evaluate the controller using the template offered by the state in ui-router

Instructions for setting up ui router: $stateProvider .state('search', { url: '/search', views: { content: { templateUrl: 'scripts/search/search-content.html', ...

Tips for simulating changing data in snapshot tests?

Two challenge are puzzling me currently: The snapshot test for a router page includes custom routers with guards specifically for logged in users. Each time I run this test, a different generated key is produced. I am using new Date() in a date pick ...

Troubleshooting Angular Unit Tests with Karma and Jasmine

I'm having difficulties writing unit tests for my new Angular Application. Here is the controller I am working on. 'use strict'; angular.module('nileLeApp') .controller('RegisterController', function ($scope, $translate ...

Using Sinon to create a mock of a function

I'm having trouble figuring out a simple task like the one below: render() { return ( <div className="messageDetail"> <div className="messageForm" > Name: <input id="senderMsgName" value={this.props.nameVa ...

Using Mocha with the --watch flag enabled causes issues with ES6 modules and results in error messages

I've been attempting to configure Mocha to automatically monitor for changes in my files using the --watch flag. I have defined two scripts in package.json as follows: "test": "mocha", "test:watch": "mocha --watch ./test ./game_logic" When I run ...

Trying out a Controller with Jasmine in Karma

I'm trying to troubleshoot a controller issue and running into an error. Error: Object # has no method 'apply'. ReferenceError: inject is not defined The unit-test.js file looks like this: define(['angular', 'myAp ...

Jasmine spying on a standalone function that is not a method of an object

What is the best way to spy on a function that is not a method of an object? In my specific case, the function callMe is not defined on the window object - it is a dependency loaded through angular. if (X) { callMe('hello'); } ...

What is the best way to test chained function calls using sinon?

Here is the code I am currently testing: obj.getTimeSent().getTime(); In this snippet, obj.getTimeSent() returns a Date object, followed by calling the getTime() method on that Date. My attempt to stub this functionality looked like this: const timeStu ...

Mastering the Art of Mocking DOM Methods with Jest

What is the best way to simulate this code snippet using Jest : useEffect(() => { document .getElementById('firstname') ?.querySelector('input-field') ?.setAttribute('type', 'password') }, []) ...

A guide on simulating an emit event while testing a Vue child component using Jest

During my testing of multiple child components, I have encountered a frustrating issue that seems to be poor practice. Each time I trigger an emit in a child component, it prompts me to import the parent component and subsequently set up all other child co ...

Testing file uploads with AngularJS unit testsAngularJS unit testing for

Unit tests in AngularJS can easily mock XHR requests using $httpBackend, making it convenient for testing. I recently encountered a situation where I needed to mock XHR for file uploads, but faced some challenges. Take a look at the following code snippe ...

Simulating dependencies of an AngularJS module in Jasmine unit tests

Currently, I'm facing a challenge with unit testing controller code within a module that has dependencies on other modules. I've been struggling to properly mock these dependencies for testing purposes. I am utilizing the Jasmine Framework and executing m ...

Before running any unit tests, I have to address all linting issues as required by ng test

Upon running ng test, the output I receive is as follows: > ng test 24 12 2019 14:20:07.854:WARN [karma]: No captured browser, open http://localhost:9876/ 24 12 2019 14:20:07.860:INFO [karma-server]: Karma v4.4.1 server started at http://0.0.0.0:9876/ ...

I can't find my unit test in the Test Explorer

I'm currently working on configuring a unit test in Typescript using tsUnit. To ensure that everything is set up correctly, I've created a simple test. However, whenever I try to run all tests in Test Explorer, no results are displayed! It appears that Vis ...

Angular 9's Jasmine Mocking Provider Featuring Unique Methods and Properties

Currently, I am attempting to mimic the functionality of the angularx-social-login npm package. My goal is for the default test to be created and passed successfully. In my test specification, the following code is included: let component: Component; l ...

Check the feature that retrieves data from a `json` file

In my util file, I have a function that imports and checks whether a given sectionUUID has a video in the JSON file. import multipleVideos from '../data/videos.json' function hasSectionMultipleVideos (sectionUUID) { return multipleVideos.vide ...

Angular Jasmine encountered an unexpected request error while using $location and $httpBackend

My goal is to unit test the functionality of $urlRouterProvider.otherwise in order to display the URL as whatever the user has entered. However, whenever I attempt to use $location in my unit test, I encounter the following error: path default rerouting s ...

Having trouble handling empty or undefined objects during unit testing with Jest?

As a beginner in unit testing, I am currently testing the length of a navigation bar. The code snippet below shows the nav bar component within a class: <AppBar className={classes.appBar} position="static"> <Toolbar className={classes.too ...

Experimenting with checking whether a function outputs a Promise

When testing a service in AngularJS, I am aiming to verify if the returned object is a Promise. My current approach involves: obj.testMethod() .should.be.instanceOf($q.defer()); ...

Managing the handling of each catch in $httpBackend.when()

I've been working on creating Jasmine unit tests for my Angular project, and I've come across a situation that I'm not quite sure how to tackle. Within my project, I have implemented a response interceptor that can retry a request if it enc ...

Error: Trying to access properties of an undefined object (specifically 'promise.data.map')

Currently, I am in the process of writing unit tests for a project built with Angular version 1.2. For my controller tests, I have set up a mockService that returns a deferred promise. One of the service methods looks like this: function getItems() { ...

Testing Vue's disabled input using Vuetify

Learning testing is a new challenge for me, and I'm navigating my way through the complexities of it. Today, I want to create a test for a Vuetify <v-text-field> component with the following structure: <v-text-field v-model="user.captio ...

Unable to view the refreshed DOM within the specifications after it has been altered

For my current project, I am working on writing a functional spec that involves using Mocha/JSDOM and making assertions with 'chai'. The specific use case I am tackling is related to the function called updateContent: When this function is executed, it i ...

Tips for testing a function within an AngularJS service using simulated data

Looking to write a Jasmine unit test for a specific function within an AngularJS service provider called shapesResolver. The goal is to create mock data for myObject and then test the function getObjectShape() using that mock data as a parameter. How can ...

The method wrapper.setValue() is not suitable for use on EL-INPUT

Attempting to call a Vue component for unit testing with Jest, trying to set a value in an input text field. Below is the content of my "file.vue" file: <el-form-item label="Nombre" data-test="id-form"> <el-input v ...

A guide to mocking Prisma using Jest mock functionality

Utilizing prisma for database interactions and eager to implement jest-mock to simulate the findMany call. https://jestjs.io/docs/jest-object#jestmockedtitem-t-deep--false brands.test.ts import { PrismaService } from "@services/mysql.service"; i ...

"An approach to testing and logging multiple times in Python with the help of -nosetest and unittest

Here is a condensed version of the issue: a = [[1,2,3][0,0,0]] b = [[1,0,1][0,0,0]] c = [[0,0,0][1,0,1]] If level 1 is [] and level 2 is [[]], my goal is to compare every list to see if their level 2's match (disregarding order). In this example, b ...

Tips on how to verify if the Angular test with native elements has produced an error

Is there a way to detect errors in an Angular test that uses native elements? The test I am running is as follows: import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { MikeComponent } from './mike.component&a ...

The Angular test spy is failing to be invoked

Having trouble setting up my Angular test correctly. The issue seems to be with my spy not functioning as expected. I'm new to Angular and still learning how to write tests. This is for my first Angular app using the latest version of CLI 7.x, which i ...

Is there a way to include parameters in JUnit tests similar to how it is done in TestNG? If so, how can this

Is it possible to incorporate parameters into JUnit tests in a similar way as done in TestNG with xml files? I am aware of parameterized tests in JUnit, but that is not what I am looking for. Currently, I handle it like this: String example = "test"; Str ...

Verify FileReader.onload function using Jasmine and AngularJS

I have a unique directive specifically designed for uploading and importing binary files. This directive listens for a change event on an <input type="file"../> element. Currently, I am facing an issue with the code coverage of my test. Although the ...

Retrieving a certain file from a module in NodeJS

A module called simpledblayer-mongo has been recently created. The functionality of this module relies on another one called simpledblayer, which provides specific functions for the database. An issue has arisen during unit testing. The problem pertains t ...

Tips for unit testing an Angular Service that is primarily responsible for redirecting to an external page from the application

My service is responsible for redirecting to a separate login page since we are implementing login as a service. function redirectToMembership() { var returnURL = $location.host(); returnURL+="/#/Authorization"; $window.location.href=Environme ...

Simulated FTP Connection Setup and Error Event in Node.js using Typescript

In my Node-Typescript-Express application, I am utilizing the FTP library to connect and retrieve files from a designated location. As part of creating unit tests, I am focusing on mocking the library to ensure coverage for code handling Ready and Error ev ...

Experiencing an issue with hasClass when conducting jest testing on react components

I've recently started using Jest to test my React components, and this is my very first test. Here's the code snippet for my component: import React from 'react'; import PropTypes from 'prop-types'; import uuidv1 from 'uuid'; import withStyles from 'react ...

scope.$digest completes before triggering scope.$watch in Karma unit tests

I am interested in testing this specific directive: .directive('uniqueDirective', function () { return { restrict: 'A', scope: { uniqueDirective: '@', tooltip: '@', placement: '@', style: '@' }, template: '<i n ...

The Quasar test fails to locate elements with a name tag>null<

I've encountered a strange issue while trying to conduct unit tests on my Quasar application. The problem seems to be that the test is unable to locate elements with the name tag, except for the q-route-tab components. I've experimented with different comp ...

Can Selenium handle gathering multiple URLs at once?

Looking to create a Smoke test for a list of URLs by checking their titles for validity. Is this achievable? class identity(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() driver = self.driver self.driver.implicitly_wait(30) @da ...

How can I configure a mocked dependency in Jest to return a specific value in a function?

I am currently working on simulating a mongoose model to facilitate unit testing for an express controller. To keep things simple, I've removed all unnecessary code and provided below the specific scenario I'm dealing with. Here's the snippet of the code t ...