0

I'm trying to test a component using angular-testing-library and I can't figure out how to mock TranslateService from @ngx-translate

My stripped down component:

import { Component } from '@angular/core'
import { TranslateService } from '@ngx-translate/core'

@Component({
  selector: 'app-my',
  template: '<p data-testid="hello" translate="global.hello"></p>',
})
export class MyComponent {
  constructor(
    public translate: TranslateService
  ) {}
}

my test:

import { TranslateService } from '@ngx-translate/core'
import { render, screen, fireEvent } from '@testing-library/angular'
import { MyComponent } from './my.component'

class TranslateServiceMock {}


describe('MyComponent', () => {

  beforeEach(async () => {
    await render(MyComponent, {
      componentProviders: [
        { provide: TranslateService, useClass: TranslateServiceMock },
      ],
    })
  })

  it('renders', async () => {
    expect(screen.getByTestId('hello')).toBeTruthy()
  })
})

getting this error:

(node:38520) UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    |     property 'element' -> object with constructor 'Object'
    |     property 'componentProvider' -> object with constructor 'Object'
    --- property 'parent' closes the circle
    at stringify (<anonymous>)
    at writeChannelMessage (internal/child_process/serialization.js:117:20)
    at process.target._send (internal/child_process.js:805:17)
    at process.target.send (internal/child_process.js:703:19)
    at reportSuccess (/Users/alondahari/loan-gurus/customer-portal/node_modules/jest-runner/node_modules/jest-worker/build/workers/processChild.js:67:11)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:38520) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:38520) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

and the tests hang.

Update

My jest.config.js:

var utils = require('ts-jest/utils')
var tsConfig = require('./tsconfig')

module.exports = {
  preset: 'jest-preset-angular',
  roots: ['<rootDir>/src/'],
  testMatch: ['**/+(*.)+(spec).+(ts)'],
  setupFilesAfterEnv: ['<rootDir>/src/test.ts'],
  collectCoverage: true,
  coverageReporters: ['html'],
  coverageDirectory: 'coverage/my-app',
  moduleNameMapper: utils.pathsToModuleNameMapper(
    tsConfig.compilerOptions.paths || {},
    {
      prefix: '<rootDir>/',
    }
  ),
}

package.json jest entry:

  "jest": {
    "preset": "jest-preset-angular"
  }
Alon Dahari
  • 1,138
  • 1
  • 9
  • 27

2 Answers2

1

Solved, using ngx-translate-testing library. Like so:

import { TranslateService } from '@ngx-translate/core'
import { render, screen, fireEvent } from '@testing-library/angular'
import { MyComponent } from './my.component'

class TranslateServiceMock {}

const translations = {
  en: {
    global: {
      submit: 'Submit'
    }
  }
}

describe('MyComponent', () => {

  beforeEach(async () => {
    await render(MyComponent, {
      componentProviders: [
        { provide: TranslateService, useClass: TranslateServiceMock },
      ],
      imports: [TranslateTestingModule.withTranslations(translations)],
    })
  })

  it('renders', async () => {
    expect(screen.getByTestId('hello')).toBeTruthy()
  })
})
Alon Dahari
  • 1,138
  • 1
  • 9
  • 27
0

Here is the complete tutorial on Unit testing in Angular using JEST. Hope this tutorial covers most of the topics in JEST Angular Unit Testing A-Z JEST Angular Unit Testing Tutorial

  • Please also report the key passages of the tutorial here on StackOverflow. Only-link answers are not accepted – Aelius Mar 24 '22 at 13:47
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/31365710) – f.khantsis Mar 29 '22 at 07:05