What steps should I take to ensure the success of this Mocha test?

I am currently utilizing angular, chai, angularmocks, mocha, and karma for testing. The test is displaying the following error:

Type error

map@[native code]

app/main.coffee:30:23 <- app/main.js:23:23

test/main.spec.coffee:59:20 <- test/main.spec.js:18:27

assert = chai.assert
expect = chai.expect

describe("The Address Book App", () ->
  describe("the proper filter", () ->
    proper = null
    beforeEach( () ->
      module("AddressBook")
      inject( ($injector)->
        proper = $injector.get("$filter")("proper")
      )
    )

    it("should proper case a string", () ->
      expect(proper("ned stark")).to.equal("Ned Stark")
    )
  )
)

main.coffee

class AddressBook
  constructor: ->
    return []

class Proper
  uppercase: (word) ->
    word[0].toUpperCase().concat(word.slice(1))

  constructor: () ->
    return (name) ->
      words = name.toString().split(" ")
      return words.map(@uppercase).join(" ")


angular.module('AddressBook', new AddressBook())
.filter('proper', [Proper])

Updated

Considering a class method 'uppercase' is more suitable for this scenario, and a slight modification in 'main.coffee' leads to a successful test.

class AddressBook
  constructor: ->
    return []

class Proper
  @uppercase: (word) ->
    word[0].toUpperCase().concat(word.slice(1))

  constructor: () ->
    return (name) ->
      words = name.toString().split(" ")
      return words.map(Proper.uppercase).join(" ")


angular.module('AddressBook', new AddressBook())
.filter('proper', [Proper])

However, if an instance method is truly required, how can the test be successfully passed?

Answer №1

The reason for this issue stems from how CoffeeScript manages the usage of the this keyword. Within your constructor, a function is being returned, but the variable @uppercase is being accessed inside that function. In this scenario, it is essential for the this keyword (i.e. the @) to point to the specific object instance under construction. Nonetheless, this consistently points to the object on which the function is invoked, which in this instance is undefined.

To rectify this, one can simply employ the fat arrow, enabling CoffeeScript to set the this keyword as intended:

class Solution
  uppercase: (word) ->
    word[0].toUpperCase().concat(word.slice(1))

  constructor: () ->
    return (name) =>
      words = name.toString().split(" ")
      return words.map(@uppercase).join(" ")

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

The function $.fn.dataTable.render.moment does not exist in npm package

I have encountered an issue with my application that I am struggling to solve: I want to format dates in my data table using Moment.js like I have done in the following script: $().ready(function() { const FROM_PATTERN = 'YYYY-MM-DD HH:mm:ss.SSS&a ...

Tips for transferring a boolean value to a generic parameter in Java?

Looking to pass a boolean value to the Generic type in order to be utilized within a condition. This is the generic type interface OptionTypeBase { [key: string]: any; } type OptionsType<OptionType extends OptionTypeBase> = ReadonlyArray<Opt ...

Can you provide guidance on utilizing the Login Event within the Electron Framework?

I need some assistance in understanding the functionality of the Event: 'login' feature within the Electron Framework. Is this similar to the Password Autofill/Remember Password feature typically found in web browsers? I'm interested in util ...

Exploring the capabilities of the Next.js router and the useRouter

import { routeHandler } from "next/client"; import { useRouteNavigator } from "next/router"; const CustomComponent = () => { const routerFromHook = useRouteNavigator(); } export default CustomComponent; Can you explain the disti ...

Issue: Bidirectional binding functionality is not functioning properly within the user interface modal

I'm currently working on displaying data in a modal, but I'm facing issues with getting two-way binding to work properly. In my HTML code: <div class="cta-actions"> <div class="action"><a class="btn btn-lg btn-max">Send a pa ...

How can the jQuery click() method be utilized?

Currently working on a web scraping project, I have managed to gather some valuable data. However, I am now faced with the challenge of looping through multiple pages. Update: Using nodeJS for this project Knowing that there are 10 pages in total, I atte ...

Tally the total number of items within an array using AngularJS

Here is my code snippet: $scope.data.months = []; angular.forEach(response, function (value, key) { $scope.data.months.push({'month':value}); }); The output of console.log(response) looks like this: Array[3] 0 : "April 2017" 1 ...

Methods for validating ajax response with Jasmine

I'm a newbie when it comes to jasmine and I'm trying to figure out how to verify if a specific node is present in the ajax response. Currently, I'm using grunt to run jasmine from the command line and have successfully tested if a function i ...

Displaying an error message in the designated errors div is necessary when the regular expression does not produce a match

Is there a way to display an error message in the errors div when the jQuery match function returns false? <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link href="form.css"> ...

BackboneJS struggles to redirect to .fail when an API request exceeds the timeout

I'm a newbie to backbone and I've come across some interesting code that adds Deferred to enable the use of promises. Take a look at the snippet below: getPatientInfo: function fetch(options) { var deferred = $.Deferred(); Backbone.Model.p ...

Unit testing Vue 3 by simulating the push() method of vue-router

As a newcomer to Vue and StackOverflow, I wanted to share my issue. While attempting to run the unit test for my application, I encountered a TypeError. The error message stated: "TypeError: Cannot read properties of undefined (reading 'push')" ...

The value of the ng-model checkbox does not update or change when the checkbox is clicked

There is a checkbox being used in the code snippet below: <input type="checkbox" ng-click="toggleShowOtherUserConfiguration()" ng-model="showOtherUserConfiguration" name="ShowOtherUserConfiguration" value="showOtherUserConfigurati ...

Using Vue.js, send information from an Ajax request to a Laravel controller for processing

As someone new to development, I have a little confusion with handling data from a multi-step form in an AJAX request on my controller. While I've been able to successfully collect all form inputs at once, I'm struggling to use the data from $req ...

What are the steps for generating website endpoints using search query outcomes?

I am currently working on a ReactJS website as a part of my web development bootcamp project. One interesting feature I have incorporated is a search functionality that uses Flask routes to connect ReactJS endpoints (../Language.js) with my Sqlite3 databa ...

Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test. The view is up and running, but I'm facing some roadblocks as I work on ...

Changes in props do not automatically update children via Ref

I'm working on a React component that needs to update whenever the width changes: import { useRef, useEffect, useState } from "react"; function Child({ containerWidth }) { console.log("CHILD", containerWidth); return <div&g ...

Issue with DWR and Android web browser

I recently encountered an issue while trying to access an application through the Android browser. The application uses DWR to maintain connections with connected clients. Everything seems to be working fine, except for the fact that if there is a 2-minut ...

Sort the results by total count in Mongoose Express Node.js after grouping by id

I have a unique collection of items: { "_id": { "$oid": "5f54b3333367b91bd09f4485" }, "items": [ { "_id": 20, "name": "Turkish Coffee", "price": ...

Using a for loop in JavaScript to dynamically generate HTML content within a Django project

Do you have a unique question to ask? Version: Django version 3.0.8 This block contains my JavaScript code: fetch(`/loadbox/${message.id}`) .then(response => response.json()) .then(dialog => { let detailcontent= `<div class=" ...

Using AJAX to handle 404 errors in Slim PHP

When I attempt to retrieve data using AJAX in my Slim PHP application, I am encountering a 404 (Not found) error in the console. The specific error message is as follows: http://localhost:8888/Project/mods/public/edit-mod/ajax/get-categories?gameID=1 404 ...