簡體   English   中英

Jest + 角度測試庫:Mock TranslateService

[英]Jest + angular-testing-library: Mock TranslateService

我正在嘗試使用 angular-testing-library 測試一個組件,但我不知道如何從@ngx-translate模擬 TranslateService

我的精簡組件:

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
  ) {}
}

我的測試:

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()
  })
})

收到此錯誤:

(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.

並且測試掛起。

更新

我的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": {
    "preset": "jest-preset-angular"
  }

已解決,使用ngx-translate-testing庫。 像這樣:

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()
  })
})

這是 Angular 中使用 JEST 進行單元測試的完整教程。 希望本教程涵蓋 JEST Angular 單元測試中的大部分主題AZ JEST Angular 單元測試教程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM