Encountering an error while testing Jasmine + Angular with Typescript: "TypeError: 'undefined' is not an object."

I'm having some difficulty while trying to test a specific service. It seems that I am struggling to match the mock response correctly:

public getCustomerDetails(customerID:string): ng.IPromise<ICustomerDetails> {
    return this.testService.getCustomerDetails(customerID).then((customerResponse:ICustomerResult) => {

        var customer = customerResponse.customers;

        var customerDetailsResult:ICustomerDetails = {
            customerNumber: customer.displayCustomerNumber,
            name: customer.name,
            userId: customer.buId,
            customerType: customer.type,
            address: customer.displayAddress
        };

        return customerDetailsResult;
    });
}

Below is the Jasmine code snippet:

describe('CustomerService', () => {
    var mockTestService: any = {};
    var $q: ng.IQService;
    var createCustomerDetailsService;
    var customerDetailsService;
    var createResolvedPromise;
    var resolvePromises;

    var serviceResponse = {
        customerNumber: 'string',
        name: 'name',
        userId: 'buId',
        customerType: 'type',
        address: 'displayAddress'
    };

    var rootScope;

    beforeEach(() => {
        module('app.customer');

        inject(( _$q_, $injector) => {
            this.$q = _$q_;
            rootScope = $injector.get('$rootScope');

            createResolvedPromise = (result) => {
                return this.$q.when(result);
            };

            resolvePromises = () => {
                rootScope.$apply();
            };

            createCustomerDetailsService = () => {
                return new app.customer.CustomerService(
                    mockRnsService);
            };
        });

    });


    it('WILL search by customer ID and return a customers details', () => {
        var searchResponsePromise;

        mockTestService.getCustomerDetails = jasmine.createSpy("getCustomerDetails").and.callFake(createResolvedPromise);
        customerDetailsService = createCustomerDetailsService();
        searchResponsePromise = customerDetailsService.getCustomerDetails('12345678');
        resolvePromises();

        expect(searchResponsePromise).toEqual(serviceResponse);
    });

});

The error message that I am encountering is:

TypeError: 'undefined' is not an object (evaluating 'customer.displayCustomerNumber')

If anyone could offer some insight into why this error is occurring, I would greatly appreciate the help. Thank you.

Answer №1

initializePromise sets up fetchUserData to return a promise with the value of the input parameter such as '987654321'. As a result, the variable userData will contain the value '987654321'. Consequently, when trying to access userData.userInfo, an error occurs because userData is not an object with a property called userInfo.

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

Angular Directive for dragging and dropping elements within an iFrame

Looking for controls to enable Drag & Drop functionality across an iFrame? The reason for needing this capability within an iframe is due to building a CMS where any "absolute" css changes on the editing page will also affect the main site. I have develop ...

What could be causing my controller method in TypeScript to throw an error message unexpectedly?

Hey there. I'm diving into TypeScript and currently working on converting an Express backend to TS. Everything was smooth sailing until I encountered some unexpected issues. Specifically, the lines const hasVoted = poll.votedBy.some((voter): boolean = ...

Even as I create fresh references, my JavaScript array object continues to overwrite previous objects

Coming from a background in c# and c++, I am facing some confusion with a particular situation. Within the scope of my function, I am creating a new object before pushing it into an 'array'. Strangely, when I create the new object, it appears to ...

Exploring the power of AngularJS for previewing multiple images

I am trying to enhance my code to allow the selection and display of multiple images on the browser instead of just one at a time. However, I'm encountering some issues with my current implementation. How can I modify my code to achieve the desired ...

What is the best way to set up the parser and plugins using ESLint's updated flat configuration?

How can ESLint be configured using the new "flat config" system (specifically with the eslint.config.js file) to work seamlessly with both @typescript-eslint/eslint-plugin and /parser? I have been struggling to make ESLint's new configuration system ...

Find the TypeScript data type of an array that may be empty

Struggling to determine the TypeScript type of data being passed into my React component. The data could either be related to cats or dogs: my-component.tsx: export const MyComponent = { props: { data: any; // Ideally looking to utilize the union type & ...

Storing numerous string labels and arrays in a TypeScript associative array

I am currently developing a mobile app using Ionic 4 where I need to store various labels and arrays in an associative array. However, I am encountering challenges when it comes to initializing the array, adding new items to it, and updating existing ones ...

executing a controller method in AngularJS

Looking to trigger a controller function from a directive tag. Check out this demo: https://jsfiddle.net/6qqfv61k/ When the 'Export to Excel' button is clicked, I need to call the dataToExport() function from appCtrl since the data is ready for ...

Angular 4 in combination with ngx-datatable is showing a 404 error for the @swimlane/ngx-datatable package

Just starting out with Angular and I kicked things off by running this command: git clone https://github.com/angular/quickstart appName I've made the upgrade to Angular 4 and everything seems to be in order. Here's the output I got after running ...

Unsure how to proceed with resolving lint errors that are causing changes in the code

Updated. I made changes to the code but I am still encountering the following error: Error Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. It is recom ...

Tips for adjusting the width of columns automatically in exceljs

One of my challenges is to automatically adjust column width using exceljs. I want the Excel sheet to be dynamic, saving only the columns specified by the user in the request. Here is the code snippet that accomplishes this: workSheet.getRow(1).values = dt ...

Exploring Angular UI Router Testability Through Resolve

Looking for some assistance with my karma setup as I am still learning. Here are the routes that I have defined: angular .module('appRouter',['ui.router']) .config(function($stateProvider,$urlRouterProvider){ ...

Is a package.json file missing dependencies?

Curious about the meaning of peerDependencies, I examined the contents of this package.json file. It relates to a library project that is distributed elsewhere. { "name": "...", "version": "...", "description": "...", "author": "...", ...

Guide to uploading files in Vue.js v3

I'm trying to implement file upload functionality using Vue.js version 3. Although I have successfully imported ref, I am unsure how to utilize it for retrieving file data? FileUploadTest.vue <template> <h1>File Upload</h1> <div ...

Angular allows for routing two distinct paths to separate components located within the same lazily loaded submodule

There are two paths available: /a and /b Both routes lead to the same child module in the parent module: // app-routing.module.ts { path: 'a', loadChildren: () => import('./m-child/m-child.module').then(m => m.ChildModu ...

What is the best way to integrate retrieved data into Next.js with TypeScript?

Hello everyone! I recently started working with Next.js and TypeScript. Currently, I'm attempting to use the map() function on data fetched from JsonPlaceholder API. Here is my implementation for getStaticProps: export const getStaticProps: GetStatic ...

Error is being thrown when Angular directives are called before the data/token is available

One of the main tasks in my app is to authenticate the user and obtain a token using a service. Currently, this service is being used in the mainController which is attached to the body element in index.html. It's crucial for this authentication proc ...

Typescript -> In a React Native project, the type of 'value' is classified as 'unknown'

While working on converting a JS file to TS within my react native project, I encountered an issue that I am struggling to resolve. The problem arises when the value['flag'] is displaying an error message stating 'value' is of type &apo ...

Exporting a object in Angular2 Using TypeScript

I've been working on a small Angular2 application using Typescript and things have been going smoothly so far. My goal is to utilize a file called config that contains all the necessary settings for the application. Here's the file in question: ...

Storing the current date() in JSON format using AngularJS

I am currently working on saving various data, including the current date, in a JSON file stored in LocalStorage. While I have been successful in saving the data, the date is saved in the ISO 8601 format: [{"date":"2014-10-13T17:55:32.953Z"}] This format ...