Jest Testing - TypeError: d не является функцией - PullRequest
0 голосов
/ 23 ноября 2018

Я пытаюсь добавить тестирование в свое приложение Electron + Vue2, написанное на TypeScript, используя ts-Jest / Jest и Chai.Я исправил предыдущие проблемы, такие как импорт не был распознан и другие.В настоящее время я сталкиваюсь с проблемой, когда при попытке запустить мой простой тест я вижу: (посмотрите в выводе для большего контекста)

Ошибка типа: d не является функцией

Это, однако, гораздо менее наглядно, чем раньше, я также не совсем уверен, на что он указывает, поскольку он, похоже, связан с этой проблемой , которая была исправлена, когда я обновил этот модуль.

Конечно, это не проблема, когда я на самом деле запускаю свое приложение, и у меня возникают проблемы с поиском чего-либо, связанного с этим, даже в связи с тем, что в моих предыдущих постах я все больше разгуливаю по поводу Jest и тому подобного.

Выход

$ npm run test

> app@1.0.0 test C:\Users\daniel\Desktop\app\app
> jest --debug --detectOpenHandles --forceExit --verbose --colors

{
  "configs": [
    {
      "automock": false,
      "browser": false,
      "cache": true,
      "cacheDirectory": "C:\\Users\\daniel\\AppData\\Local\\Temp\\jest",
      "clearMocks": false,
      "coveragePathIgnorePatterns": [
        "\\\\node_modules\\\\"
      ],
      "detectLeaks": false,
      "detectOpenHandles": true,
      "errorOnDeprecated": false,
      "filter": null,
      "forceCoverageMatch": [],
      "globals": {
        "ts-jest": {
          "tsConfig": "./src/app/tsconfig.json"
        },
        "NODE_ENV": "test"
      },
      "haste": {
        "providesModuleNodeModules": []
      },
      "moduleDirectories": [
        "node_modules",
        "src"
      ],
      "moduleFileExtensions": [
        "js",
        "ts",
        "json",
        "node",
        "html"
      ],
      "moduleNameMapper": {},
      "modulePathIgnorePatterns": [],
      "modulePaths": [
        "C:\\Users\\daniel\\Desktop\\app\\app\\src",
        "C:\\Users\\daniel\\Desktop\\app\\app\\node_modules"
      ],
      "name": "49c9f95751e84975b9ee85f166b8dbdd",
      "prettierPath": "C:\\Users\\daniel\\Desktop\\app\\app\\node_modules\\prettier\\index.js",
      "resetMocks": false,
      "resetModules": false,
      "resolver": null,
      "restoreMocks": false,
      "rootDir": "C:\\Users\\daniel\\Desktop\\app\\app",
      "roots": [
        "C:\\Users\\daniel\\Desktop\\app\\app"
      ],
      "runner": "jest-runner",
      "setupFiles": [],
      "setupTestFrameworkScriptFile": null,
      "skipFilter": false,
      "snapshotSerializers": [],
      "testEnvironment": "C:\\Users\\daniel\\Desktop\\app\\app\\node_modules\\jest-environment-node\\build\\index.js",
      "testEnvironmentOptions": {},
      "testLocationInResults": false,
      "testMatch": [
        "**/__tests__/**/*.js?(x)",
        "**/?(*.)+(spec|test).js?(x)",
        "**/__tests__/**/*.ts?(x)",
        "**/?(*.)+(spec|test).ts?(x)"
      ],
      "testPathIgnorePatterns": [
        "\\\\build\\\\",
        "\\\\config\\\\",
        "\\\\data\\\\",
        "\\\\dist\\\\",
        "\\\\node_modules\\\\",
        "\\\\test\\\\",
        "\\\\vendor\\\\"
      ],
      "testRegex": "",
      "testRunner": "C:\\Users\\daniel\\Desktop\\app\\app\\node_modules\\jest-jasmine2\\build\\index.js",
      "testURL": "http://localhost",
      "timers": "real",
      "transform": [
        [
          "^.+\\.html$",
          "C:\\Users\\daniel\\Desktop\\app\\app\\config\\htmlLoader.js"
        ],
        [
          "^.+\\.[tj]sx?$",
          "C:\\Users\\daniel\\Desktop\\app\\app\\node_modules\\ts-jest\\dist\\index.js"
        ]
      ],
      "transformIgnorePatterns": [
        "node_modules\\\\(?!(bootstrap-vue)\\\\)"
      ],
      "watchPathIgnorePatterns": []
    }
  ],
  "globalConfig": {
    "bail": false,
    "changedFilesWithAncestor": false,
    "collectCoverage": false,
    "collectCoverageFrom": null,
    "coverageDirectory": "C:\\Users\\daniel\\Desktop\\app\\app\\coverage",
    "coverageReporters": [
      "json",
      "text",
      "lcov",
      "clover"
    ],
    "coverageThreshold": null,
    "detectLeaks": false,
    "detectOpenHandles": true,
    "errorOnDeprecated": false,
    "expand": false,
    "filter": null,
    "forceExit": true,
    "globalSetup": null,
    "globalTeardown": null,
    "listTests": false,
    "maxWorkers": 3,
    "noStackTrace": false,
    "nonFlagArgs": [],
    "notify": false,
    "notifyMode": "always",
    "passWithNoTests": false,
    "projects": null,
    "rootDir": "C:\\Users\\daniel\\Desktop\\app\\app",
    "runTestsByPath": false,
    "skipFilter": false,
    "testFailureExitCode": 1,
    "testPathPattern": "",
    "testResultsProcessor": null,
    "updateSnapshot": "new",
    "useStderr": false,
    "verbose": true,
    "watch": false,
    "watchman": true
  },
  "version": "23.6.0"
}
 FAIL  src/app/tests/app-window.component.spec.ts
  ● Test suite failed to run

    TypeError: d is not a function

      3 | import { Prop } from 'vue-property-decorator'
      4 | import {
    > 5 |   ipcMainToRendererAppChannel,
        |                                         ^
      6 |   IpcMainToRendererAppMessage
      7 | } from '../../../contracts/appAppMessages'
      8 | import {

      at Object.<anonymous>.__decorate (src/app/features/webview/webview.component.ts:5:95)
      at Object.<anonymous> (src/app/features/webview/webview.component.ts:23:30)
      at Object.<anonymous> (src/app/features/app-application-content/app-application-content.component.ts:24:1)
      at Object.<anonymous> (src/app/features/app-content/app-content.component.ts:9:1)

  console.log src/shared/Log.ts:4
    not able to resolve rtc url ReferenceError: fetch is not defined
        at Object.getJson (C:\Users\daniel\Desktop\app\app\src\shared\ProtocolRequests.ts:28:5)
        at Function.getappConfig (C:\Users\daniel\Desktop\app\app\src\shared\Config.protocol.ts:27:35)
        at Object.getConfig (C:\Users\daniel\Desktop\app\app\src\renderer\config.ts:7:57)
        at discoverRTCUrl (C:\Users\daniel\Desktop\app\app\src\renderer\rtc.ts:7:35)
        at Object.<anonymous> (C:\Users\daniel\Desktop\app\app\src\renderer\rtc.ts:10:49)
        at Runtime._execModule (C:\Users\daniel\Desktop\app\app\node_modules\jest-runtime\build\index.js:694:13)
        at Runtime.requireModule (C:\Users\daniel\Desktop\app\app\node_modules\jest-runtime\build\index.js:376:14)
        at Runtime.requireModuleOrMock (C:\Users\daniel\Desktop\app\app\node_modules\jest-runtime\build\index.js:463:19)
        at Object.<anonymous> (C:\Users\daniel\Desktop\app\app\src\app\features\app-application-content\app-application-content.component.ts:15:1)
        at Runtime._execModule (C:\Users\daniel\Desktop\app\app\node_modules\jest-runtime\build\index.js:694:13)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        3.218s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! app@1.0.0 test: `jest --debug --detectOpenHandles --forceExit --verbose --colors`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the app@1.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\daniel\AppData\Roaming\npm-cache\_logs\2018-11-23T15_31_12_028Z-debug.log

jest.config.js

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'node',
  verbose: true,
  moduleDirectories: ['node_modules', 'src'],
  modulePaths: ['<rootDir>/src', '<rootDir>/node_modules'],
  moduleFileExtensions: ['js', 'ts', 'json', 'node', 'html'],
  transform: {
    '^.+\\.html$': '<rootDir>/config/htmlLoader.js'
  },
  transformIgnorePatterns: ['node_modules/(?!(bootstrap-vue)/)'],
  testPathIgnorePatterns: [
    '/build/',
    '/config/',
    '/data/',
    '/dist/',
    '/node_modules/',
    '/test/',
    '/vendor/'
  ],
  globals: {
    'ts-jest': {
      tsConfig: './src/app/tsconfig.json'
    },
    NODE_ENV: 'test'
  }
}

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "outDir": "./built/",
    "sourceMap": true,
    "strict": true,
    "moduleResolution": "node",
    "target": "ES2017",
    "experimentalDecorators": true,
    "noEmitHelpers": false,
    "noImplicitAny": false,
    "emitDecoratorMetadata": true,
    "allowSyntheticDefaultImports": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "esModuleInterop": true,
    "lib": ["es2017", "dom"],
    "include": [
      "**/*",
      "../types/**/*",
      "../../node_modules/bootstrap-vue/**/*",
      "../../node_modules/electron/**/*"
    ]
  }
}

тест

import { expect } from 'chai'
import 'jest'
import { appWindowComponent } from './app-window.component'

const appWindowComponent = new appWindowComponent()

describe('Test: Set Title Function', () => {
  it('should set the variable title to the passed variable', () => {
    const title = 'this is a test'
    appWindowComponent.setTitle(title)
    expect(appWindowComponent.title).to.equal(title)
  })
})

Правка # 1

После выполнения некоторых дополнительных операций я удалил импортчтобы увидеть, если шутка дала мне неправильный указатель, и это было:

FAIL  src/app/tests/app-window.component.spec.ts
  ● Test suite failed to run

    TypeError: d is not a function

      3 | import Component from 'vue-class-component'
      4 |
    > 5 | import { Prop } from 'vue-property-decorator'
        |                                                                            ^
      6 |
      7 | import { ipcMainToRendererAppChannel,
      8 |   IpcMainToRendererAppMessage

      at Object.<anonymous>.__decorate (src/app/features/webview/webview.component.ts:5:95)
      at Object.<anonymous> (src/app/features/webview/webview.component.ts:25:30)
      at Object.<anonymous> (src/app/features/app-application-content/app-application-content.component.ts:24:1)
      at Object.<anonymous> (src/app/features/app-content/app-content.component.ts:9:1)

Edit # 2

используя Jest-Fetch-Mock Iизбавился от

console.log src/shared/Log.ts:4
    not able to resolve rtc url ReferenceError: fetch is not defined
        at Object.getJson (C:\Users\daniel\Desktop\app\app\src\shared\ProtocolRequests.ts:28:5)
        at Function.getappConfig (C:\Users\daniel\Desktop\app\app\src\shared\Config.protocol.ts:27:35)
        at Object.getConfig (C:\Users\daniel\Desktop\app\app\src\renderer\config.ts:7:57)
        at discoverRTCUrl (C:\Users\daniel\Desktop\app\app\src\renderer\rtc.ts:7:35)
        at Object.<anonymous> (C:\Users\daniel\Desktop\app\app\src\renderer\rtc.ts:10:49)
        at Runtime._execModule (C:\Users\daniel\Desktop\app\app\node_modules\jest-runtime\build\index.js:694:13)
        at Runtime.requireModule (C:\Users\daniel\Desktop\app\app\node_modules\jest-runtime\build\index.js:376:14)
        at Runtime.requireModuleOrMock (C:\Users\daniel\Desktop\app\app\node_modules\jest-runtime\build\index.js:463:19)
        at Object.<anonymous> (C:\Users\daniel\Desktop\app\app\src\app\features\app-application-content\app-application-content.component.ts:15:1)
        at Runtime._execModule (C:\Users\daniel\Desktop\app\app\node_modules\jest-runtime\build\index.js:694:13)
...