Sophie and ridiculing preset characteristics

Consider the following files/code:

Employee.ts

export class Employee {
    id: string;
    firstName: string;
    lastName: string;
    isEmployed: boolean = true;
    isManager: boolean = false;

    public static fullName = ():string => this.firstName + ' ' + this.lastName;
}

JobHistory.ts

import { Employee } from './employee';

export class JobHistory {
   public propX: string;
   public propY: string;

   public getJobRecord = (e: Employee): any => { 
      // perform actions
      // return job history
   }; 
}

FormatterUtility.ts

import { Employee } from './employee';
import { JobHistory } from './jobHistory';

export class FormatterUtility {
   public formatJobData(e: Employee) {
       let jh: JobHistory = new JobHistory();
       let jobData = jh.getJobRecord(e);

       // modify data format
       // return formatted data
   }
}

I am working on creating a unit test for the formatJobData method. However, I'm struggling to mock out JobHistory and its properties.

Here's my progress so far:

FormatterUtility.spec.ts

describe('formatJobData', () => {
   let fakeJobHistory = {
      propX: '',
      propY: ''
   };
   let sandbox;
   let formatterUtil;

   beforeEach(() => {
      sandbox = sinon.createSandbox();
      sandbox.stub(JobHistory, "prototype").value(fakeJobHistory);
   });

   afterEach(() => {
      sandbox.restore();
   });

   it('should perform certain task', () => {
       // create employee object
       formatterUtil = new FormatterUtility();
       var result = formatterUtil.formatJobData(employee);

       console.log(result);
   });
});

I've attempted using stubs and sandbox.replace, but I can't seem to override the default properties or methods of JobHistory.

Currently, the above code throws an exception in Phantom 2.1.1:

TypeError: Trying to alter enumerable attribute of unconfigurable property.

Furthermore, the console.log output in my test displays all the default properties of JobHistory rather than the changed values.

What could be the issue here? Am I missing something important?

Answer №1

Due to my webpack setup, I found myself relying on ts-mock-imports. Grateful for the suggestion!

Answer №2

Utilizing only Sinon may not fulfill all of your needs. It is essential to incorporate additional tools for mocking imports, such as genMockFromModule in Jest or proxyquire.

Sinon serves as a convenient method for creating stubs, but it lacks knowledge about the structure of your module. Therefore, you must devise a way to effectively pass your Sinon-mocked class to the module being tested.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on distinguishing between two dates in Ionic3 using either date-fns or Moment libraries

How can I calculate the difference between two dates to determine the end of an employee's service? Similar Question: What is the best way to find the day difference between two dates using Ionic 3? I am looking for a solution on how to get the exac ...

Preventing spam links on a registration form using JavaScript

Our website has a membership registration form with JavaScript validation. Unfortunately, the last two registrations have included malware links in the address and notes fields. Using Captcha is not an effective solution to prevent this issue. I've be ...

Updating certain fields in AngularJS with fresh data

I am facing a challenge with the following code snippet: <div ng-controller="postsController"> <div id = "post_id_{{post.postid}}" class = "post" ng-repeat="post in posts"> ...... <div class="comments"> < ...

Getting the value of an element using a string in JQuery

How can I achieve the following using JQuery? var test = "'#ISP'"; alert($(test).val()); I am receiving a "Syntax error, unrecognized expression." I believe I might be overlooking something here. Thank you in advance! ...

What is causing the malfunction in this code? (Regarding the key and value variable objects)

var elements = []; var attribute1 = $(index).attr('class'); //or any string var attribute2 = $(index).html(); //or any string elements.push({ attribute1: attribute2 }); When I run this code, the output I receive is: this Why am I unable to set ...

Using Vuetify's v-chip within a data table's array

Just starting out with vuetify and I'm looking for help on how to set a specific value for a v-chip in my table. <v-data-table class="page__table" :headers="headers" :items="references" > <v-chip ...

Challenges with Scaling HTML5 Video onto Canvas

Attempting to extract a frame from an html5 video to generate a thumbnail, but encountering peculiar outcomes when the image is rendered onto canvas. The issue lies in the fact that the canvas displays only a greatly magnified portion of the video! Refer ...

Sending data in chunks using Vue.js

I'm interested in sending the data in chunks. Currently, what I send to the server looks like this: for loop - 1, 2, 3. However, the server receives it asynchronously as 3, 1, 2 and I need it to be received synchronously in the order of my for loop: 1 ...

conditionally manipulate colspan attribute with AngularJS

Is there a way to dynamically change the value of the 'th' colspan attribute based on a condition in Angular? I have attempted the following code, but it doesn't seem to be working. Can someone point out what might be incorrect here? <t ...

Ways to determine the text field value without the need for a submit button

I need help with a calculation that doesn't require a submit button. I want to automatically calculate and display the total value in a text field based on the weight, height, and number of pieces entered by the user without having to refresh the page ...

Error in Three.js: Incorrect values retrieved for object's position, rotation, and scale

Working with a three.js object in my scene, I utilize the THREE.TransformControls to rotate, scale, and move it. After positioning the object, I need to save the values of rotation, position, and scale. The code snippet below shows how I am currently retri ...

What is the best way to conceal an ag-grid column when viewing on a mobile

I am attempting to conceal a column in ag-grid when viewing it on mobile devices. For my vue.js application, I have tried using the code snippet below, but unfortunately, it is not functioning as expected. { headerName: "Action", field: "action", minWidt ...

Encountering Undefined Value when Parsing JSON with JavaScript

Currently, I am immersed in a project that involves using Javascript and JSON Objects to dynamically populate data in a popup modal. The process unfolds as follows: when a user clicks on the title of a feedback issue, the relevant data is fetched from the ...

Retrieving information upon page loading and setting it as select options within a Vue JS environment

Currently, I am working on a straightforward form that includes a select type form. This specific form is initially created without any options as I intend to dynamically populate them from the backend later. Below is the code snippet for reference: < ...

What is the best way to adjust the size of a kendo ui combobox?

Is there a way to adjust the width of the kendo ui combobox? My current version is 2012.3.1114 I've attempted to modify it using the following CSS: #options { padding: 30px; } #options h3 { font-size: 1em; font-weight: bold; margin: 2 ...

Developing ES6 modules in C++ using Node.js

Here is a previous example showcasing how to create a Node.js addon in C++: https://nodejs.org/api/addons.html You can use node-gyp to build it into a common JS module, which works well with the 'require' function. However, when trying to impo ...

The term 'includes' is not present within type 'any' in Reactjs

I am currently working on a web page that is designed to display data and allow users to filter it. The data display aspect is functioning correctly, but I am encountering issues when attempting to implement the filtering feature. Specifically, the proble ...

error TS2304: The term 'MediaRecorder' is not recognized

How can I add audio recording capability to my Angular application using media recorder? Unfortunately, I am encountering the following error: Error TS2304: 'MediaRecorder' cannot be found If anyone knows a solution for this issue, your help w ...

How to use a string condition to filter a list of objects in Javascript?

Below is the structure of the object: var objList = [ { "age": 19, "valueField": 34, "booleanField": false }, { "age": 15, "valueField": 5, "booleanField": false }, { "age": 22, "valueField": 17, "booleanField": true } ]; Given the condition ...

Trouble arises when trying to open a new window using the Angular 8 CDK

I am attempting to open my component in a new window, similar to this example: https://stackblitz.com/edit/angular-open-window However, when the window opens, my component is not displayed and I receive the following error in the console: Error: Must pro ...