Related
I'm creating unit testing for a React native application, and what happens is, after the test initiate , it hangs , without any response from the terminal . I've tried to use --forceExit , --detectOpenHandles to log any problem. but the terminal continues as follow:
I've Intellij IDE , and running the same test on it I've this result
Note that where is written Running Tests... it's shows a loading icon, the test continues running on Intellij even after the test were completed.
here's the code of my testing :
/**
* #jest-environment jsdom
*/
import React from 'react';
import { mount, ReactWrapper, shallow } from 'enzyme';
import AnotherComponent from 'components/AnotherComponent';
// #ts-ignore
import { mocking } from './helpers/mockedTheme';
import TestComponent from 'components/TestComponent';
export const shallowWithTheme = (children: any) => (
// #ts-ignore
shallow(children, { mocking })
);
describe('Test Components', () => {
describe('Test Component', ()=>{
it('Test shallow with theme', () => {
const element = shallowWithTheme(<TestComponent componentProp={"test"}/>);
//#ts-ignore
expect(element).toExist();
});
});
describe('Test AnotherComponent', () =>{
it('AnotherComponent with button', () => {
const wrapper = shallowWithTheme(
<AnotherComponent icon="qr-code"
title='component title'
description='component description'
buttonText='go'
/>);
// #ts-ignore
expect(wrapper).toExist();
});
it('AnotherComponent without button', () => {
const wrapper = shallow(
<AnotherComponent icon="qr-code"
title='component title'
description='component description'
/>);
//#ts-ignore
expect(wrapper).toExist();
});
});
});
The components AnotherComponent and TestComponent are nested with another styled.components eg,:
\\ TestComponent
import React from 'react';
import { MainContentView } from 'components/TestComponent/TestComponent.styles';
import { throwJSError } from 'reduxRoot/util/error';
import { withTheme } from 'styled-components/native';
import { Text } from 'react-native';
class TestComponent extends React.Component {
render() {
try {
return (
<MainContentView>
<Text>Text</Text>
</MainContentView>
);
} catch (err) {
throwJSError(err, 'TestComponent/render');
return null;
}
}
}
export default withTheme(TestComponent);
The style MainContentView is a styled.component eg.:
export const MainContentView = styled.View` flex: 1; backgroundColor: #FFFFFF;`;
here my jest ---debug
{
"configs": [
{
"automock": false,
"browser": false,
"cache": true,
"cacheDirectory": "/private/var/folders/rk/rnc3852s3y56rx7bypry2qz92b2nhd/T/jest_j25hjh",
"clearMocks": false,
"coveragePathIgnorePatterns": [
"/node_modules/"
],
"cwd": "<root-to-my-project>",
"dependencyExtractor": null,
"detectLeaks": false,
"detectOpenHandles": true,
"errorOnDeprecated": false,
"filter": null,
"forceCoverageMatch": [],
"globalSetup": null,
"globalTeardown": null,
"globals": {
"ts-jest": {
"babelConfig": true,
"isolatedModules": true
}
},
"haste": {
"defaultPlatform": "ios",
"platforms": [
"android",
"ios",
"native"
],
"hasteImplModulePath": "<root-to-my-project>/node_modules/react-native/jest/hasteImpl.js",
"providesModuleNodeModules": [
"react-native"
]
},
"moduleDirectories": [
"node_modules"
],
"moduleFileExtensions": [
"js",
"json",
"jsx",
"ts",
"tsx",
"node"
],
"moduleNameMapper": [
[
"reduxRoot(.*)$",
"<root-to-my-project>/redux$1"
],
[
"screens(.*)$",
"<root-to-my-project>/src/screens$1"
],
[
"^React$",
"<root-to-my-project>/node_modules/react/index.js"
]
],
"modulePathIgnorePatterns": [
"<root-to-my-project>/node_modules/react-native/Libraries/react-native/"
],
"name": "a1c9dcb3024a2c47c9517df7e59341e3",
"prettierPath": "prettier",
"resetMocks": false,
"resetModules": false,
"resolver": null,
"restoreMocks": false,
"rootDir": "<root-to-my-project>",
"roots": [
"<root-to-my-project>"
],
"runner": "jest-runner",
"setupFiles": [
"<root-to-my-project>/node_modules/react-native/jest/setup.js",
"<root-to-my-project>/native/node_modules/react-native-gesture-handler/jestSetup.js"
],
"setupFilesAfterEnv": [
"<root-to-my-project>/jest.setup.js"
],
"skipFilter": false,
"snapshotSerializers": [],
"testEnvironment": "<root-to-my-project>/node_modules/jest-environment-node/build/index.js",
"testEnvironmentOptions": {},
"testLocationInResults": false,
"testMatch": [
"**/__tests__/*.(ts|tsx|js)"
],
"testPathIgnorePatterns": [
"/node_modules/"
],
"testRegex": [],
"testRunner": "<root-to-my-project>/node_modules/jest-jasmine2/build/index.js",
"testURL": "http://localhost",
"timers": "real",
"transform": [
[
"^.+\\.tsx?$",
"<root-to-my-project>/node_modules/ts-jest/dist/index.js"
],
[
"\\.js$",
"<root-to-my-project>/node_modules/react-native/jest/preprocessor.js"
],
[
"^.+\\.(js|ts|tsx)$",
"<root-to-my-project>/node_modules/babel-jest/build/index.js"
],
[
"^.+\\.(bmp|gif|jpg|jpeg|mp4|png|psd|svg|webp)$",
"<root-to-my-project>/node_modules/react-native/jest/assetFileTransformer.js"
]
],
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-clone-referenced-element|#react-native-community)"
],
"watchPathIgnorePatterns": []
}
],
"globalConfig": {
"bail": 0,
"changedFilesWithAncestor": false,
"collectCoverage": false,
"collectCoverageFrom": null,
"coverageDirectory": "<root-to-my-project>/coverage",
"coverageReporters": [
"json",
"text",
"lcov",
"clover"
],
"coverageThreshold": null,
"detectLeaks": false,
"detectOpenHandles": true,
"errorOnDeprecated": false,
"expand": false,
"filter": null,
"globalSetup": null,
"globalTeardown": null,
"json": false,
"listTests": false,
"maxConcurrency": 5,
"maxWorkers": 3,
"noStackTrace": false,
"nonFlagArgs": [],
"notify": false,
"notifyMode": "failure-change",
"passWithNoTests": false,
"projects": null,
"rootDir": "<root-to-my-project>",
"runTestsByPath": false,
"skipFilter": false,
"testFailureExitCode": 1,
"testPathPattern": "",
"testResultsProcessor": null,
"testSequencer": "<root-to-my-project>/node_modules/#jest/test-sequencer/build/index.js",
"updateSnapshot": "new",
"useStderr": false,
"verbose": true,
"watch": false,
"watchman": true
},
"version": "24.9.0"
}
And last but not least , my jest.setup.js to mock all I need to run my enviroment:
import { NativeModules } from 'react-native';
import 'jest-styled-components';
import 'react-native';
import 'jest-enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { configure } from 'enzyme';
/**
* Set up Enzyme to mount to DOM, simulate events,
* and inspect the DOM in tests.
*/
configure({ adapter: new Adapter() });
/**
* Set up DOM in node.js environment for Enzyme to mount to
*/
const { JSDOM } = require('jsdom');
const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;
function copyProps(src, target) {
Object.defineProperties(target, {
...Object.getOwnPropertyDescriptors(src),
...Object.getOwnPropertyDescriptors(target),
});
}
global.window = window;
global.document = window.document;
global.navigator = {
userAgent: 'node.js',
};
copyProps(window, global);
jest.mock('react-navigation/src/routers/KeyGenerator', () => ({
generateKey: jest.fn(() => 123),
}));
jest.mock('./node_modules/react-native-reanimated/src/ReanimatedEventEmitter');
jest.mock('./node_modules/react-native-reanimated/src/ReanimatedModule');
jest.mock('react-native-gesture-handler', () =>({
State: jest.fn(),
TapGestureHandler: jest.fn()
}));
NativeModules.RNCNetInfo = {
getCurrentState: jest.fn(() => Promise.resolve()),
addListener: jest.fn(),
removeListeners: jest.fn()
};
jest.mock('react-native-device-info', () => {
return {
getVersion: jest.fn(() => Promise.resolve('1.0')),
getApplicationName: jest.fn(() => Promise.resolve('My App')),
getModel: jest.fn(() => Promise.resolve('iPhone 11')),
hasNotch: jest.fn(),
};
});
jest.mock('services/theme/scaling', () => ({
scale: jest.fn()
})
);
jest.mock('services/theme/styles', () => ({
themeVal: jest.fn()
})
);
NativeModules.StatusBarManager = {
HEIGHT : 20,
getHeight: jest.fn()
};
NativeModules.ParentBridge ={
partnerId: jest.fn()
};
NativeModules.CTNConfig = { buildEnvironment: 'Development'};
So. Has someone knows how to configure properly my code to be able to see my unit testing finishing and not hanging anymore?
ps.: I've note I've recieving a warning message, don't know this is related on the reasons the test is hanging:
Warning: Async Storage has been extracted from react-native core and will be removed in a future release. It can now be installed and imported from '#react-native-community/async-storage' instead of 'react-native'. See https://github.com/react-native-community/react-native-async-storage```
After I installed jest, setup babel, eslint, jest-setup and etc then I checked jest works fine.
But when I npm run serve(vue-clie-service serve), It includes test folders(__test __/abc.spec.js).
I would like to exclude all files below __test
__ direcotry when npm run serve.
It occurs error now jest is not defined. describe is note defined...
#jest.config.js
module.exports = {
moduleFileExtensions: [
"js",
"json",
"vue",
],
transform: {
".*\\.(vue)$": "vue-jest",
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".+\\.(css|styl|less|sass|scss)$": "jest-transform-css",
},
moduleNameMapper: {
"^#/(.*)$": "<rootDir>/src/$1",
"\\.(css|less|scss|sass)$": "identity-obj-proxy",
},
transformIgnorePatterns: ["<rootDir>/node_modules/"],
collectCoverage: false,
collectCoverageFrom: ["**/*.{js,vue}", "!**/node_modules/**"],
coverageReporters: ["html", "text-summary"],
testMatch: [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
"<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}",
],
setupFilesAfterEnv: ["<rootDir>/jest-setup.js"],
preset: "#vue/cli-plugin-unit-jest",
};
# main.js
import Vue from "vue";
import "./plugins/axios";
import App from "./App";
import router from "./router";
import store from "./store";
import i18n from "./plugins/i18n";
import vuetify from "./plugins/vuetify";
import "#/assets/styles/_global.scss";
import "#babel/polyfill";
Vue.config.productionTip = false;
new Vue({
i18n,
router,
store,
vuetify,
render: h => h(App),
}).$mount("#app");
# vue.config.js
const path = require("path");
const ansiRegex = require("ansi-regex");
module.exports = {
devServer: {
proxy: {
"/api": {
target: process.env.VUE_APP_TARGET,
changeOrigin: true,
},
},
},
configureWebpack: {
resolve: {
alias: {
"#": path.join(__dirname, "src/"),
},
},
},
css: {
loaderOptions: {
scss: {
prependData: "#import \"#/assets/styles/_global.scss\";",
},
},
},
transpileDependencies: [
"vuetify",
ansiRegex,
],
};
i try to help you but could you share jest.config.js or another config file.
Could you try this code on config file.
Attention: You must edit your folder path and if you don't use Typescript, you delete ts and tsx.
#jest.config.js
module.exports = {
preset: 'ts-jest',
verbose: true,
collectCoverage: true,
collectCoverageFrom: [
'**/*.{ts,vue}',
'!**/node_modules/**',
'!**/vendor/**'
],
coverageReporters: [
'json', 'lcov', 'text'
],
moduleFileExtensions: [
'js',
'jsx',
'json',
'vue',
'ts',
'tsx'
],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.tsx?$': 'ts-jest',
'^.+\\.ts?$': 'ts-jest',
'^.+\\.jsx?$': 'babel-jest',
'^.+\\.js?$': 'babel-jest'
},
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1',
'^#/application/(.*)$': '<rootDir>/src/application/$1',
'^#/common/(.*)$': '<rootDir>/src/common/$1',
'^#/components/(.*)$': '<rootDir>/src/components/$1'
},
transformIgnorePatterns: [
'/node_modules/(?!(tiny-slider)/(.*)$)'
],
snapshotSerializers: [
'jest-serializer-vue'
],
testMatch: [
'**/src/**/*.spec.(js|jsx|ts|tsx)',
'**/src/application/**/*.spec.(js|jsx|ts|tsx)',
'**/src/common/**/*.spec.(js|jsx|ts|tsx)',
'**/src/components/**/*.spec.(js|jsx|ts|tsx)',
'**/tests/unit/**/*.spec.(js|jsx|ts|tsx)'
],
testURL: 'http://localhost:8080/'
}
In my Vue app test file I'm pulling in import Users from '#/models/user';
I've cleared the cache before running the test but it doesn't seem to help..
In the src/models/user.js file I have:
export default class Users {
}
When I run the test I get the error:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export default function _classCallCheck(instance, Constructor) {
^^^^^^
SyntaxError: Unexpected token export
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
at Object.<anonymous> (src/models/user.js:10:47)
jest.config.js is as follows:
module.exports = {
moduleFileExtensions: [
'js',
'jsx',
'json',
'vue'
],
transform: {
'^.+\\.vue$': 'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
'^.+\\.jsx?$': 'babel-jest'
},
moduleNameMapper: {
'^#/(.*)$': '<rootDir>/src/$1'
},
snapshotSerializers: [
'jest-serializer-vue'
],
testMatch: [
'**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
],
testURL: 'http://localhost/'
}
and my babel.config.js is:
module.exports = {
presets: [
'#vue/app',
'#babel/preset-env'
]
}
How do you instantiate a provider in TestBed.configureTestingModule() with an instance of another provider?
An example (doesn't work obviously):
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: ServiceOne, useValue: new ServiceOne('parameterOne')},
{ provide: ServiceTwo, useValue: new ServiceTwo(TestBed.get(ServiceOne), 'parameterTwo')}
]
});
});
Use a factory provider
providers: [
{ provide: ServiceOne, useValue: new ServiceOne('parameterOne')},
{
provide: ServiceTwo,
deps: [ ServiceOne ],
useFactory: (serviceOne: ServiceOne) => {
return new ServiceTwo(serviceOne, 'parameterTwo')
}
}
]
I struggle http client works, firstly i tried http module but when i searched examples, I saw they did with jsonp. Briefly, when i tried this jsonp i get this error :
Error: Uncaught (in promise): Error: Error in ./MusteriComponent class MusteriComponent **- inline template:0:0 caused by: No provider for Jsonp!**
Stack trace:
resolvePromise#http://localhost:4200/main.bundle.js:101640:31
makeResolver/<#http://localhost:4200/main.bundle.js:101617:13
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invoke#http://localhost:4200/main.bundle.js:101414:19
NgZoneImpl/this.inner<.onInvoke#http://localhost:4200/main.bundle.js:65487:28
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invoke#http://localhost:4200/main.bundle.js:101413:19
Zone$1</Zone</Zone.prototype.run#http://localhost:4200/main.bundle.js:101307:24
scheduleResolveOrReject/<#http://localhost:4200/main.bundle.js:101673:52
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask#http://localhost:4200/main.bundle.js:101447:23
NgZoneImpl/this.inner<.onInvokeTask#http://localhost:4200/main.bundle.js:65478:28
Zone$1</ZoneDelegate</ZoneDelegate.prototype.invokeTask#http://localhost:4200/main.bundle.js:101446:23
Zone$1</Zone</Zone.prototype.runTask#http://localhost:4200/main.bundle.js:101347:28
drainMicroTaskQueue#http://localhost:4200/main.bundle.js:101579:25
ZoneTask/this.invoke#http://localhost:4200/main.bundle.js:101519:25
app-module
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule} from '#angular/http';
import { AppComponent } from './app.component';
import { MainModule } from './main/main.module'
import { routing,
appRoutingProviders } from './app.routing';
import { LoginComponent } from './login/login.component';
import {InMemoryWebApiModule} from "angular2-in-memory-web-api";
import {CosmoData} from "./cosmo-data"
#NgModule({
declarations: [
LoginComponent,
AppComponent
],
imports: [
MainModule,
BrowserModule,
FormsModule,
HttpModule,
routing,
InMemoryWebApiModule.forRoot(CosmoData)
],
providers: [
appRoutingProviders
],
bootstrap: [AppComponent]
})
export class AppModule { }
package-json
{
"name": "cosmo-client",
"version": "0.0.0",
"license": "MIT",
"angular-cli": {},
"scripts": {
"start": "ng serve",
"lint": "tslint \"src/**/*.ts\"",
"test": "ng test",
"pree2e": "webdriver-manager update",
"e2e": "protractor"
},
"private": true,
"dependencies": {
"#angular/common": "2.0.0",
"#angular/compiler": "2.0.0",
"#angular/core": "2.0.0",
"#angular/forms": "2.0.0",
"#angular/http": "2.0.0",
"#angular/platform-browser": "2.0.0",
"#angular/platform-browser-dynamic": "2.0.0",
"#angular/router": "3.0.0",
"angular2-in-memory-web-api": "0.0.20",
"core-js": "^2.4.1",
"primeng": "^1.0.0-beta.16",
"rxjs": "5.0.0-beta.12",
"ts-helpers": "^1.1.1",
"zone.js": "^0.6.23"
},
"devDependencies": {
"#types/jasmine": "^2.2.30",
"angular-cli": "1.0.0-beta.14",
"codelyzer": "~0.0.26",
"jasmine-core": "2.4.1",
"jasmine-spec-reporter": "2.5.0",
"karma": "1.2.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-remap-istanbul": "^0.2.1",
"protractor": "4.0.5",
"ts-node": "1.2.1",
"tslint": "3.13.0",
"typescript": "2.0.2",
"webpack": "2.1.0-beta.22"
}
}
gib-service
import { Injectable } from '#angular/core';
import {Observable} from "rxjs";
import {Response,Http,Jsonp} from "#angular/http";
import any = jasmine.any;
#Injectable()
export class GibService {
constructor(private http:Http,private jsonp:Jsonp) { }
items:any;
private handleError(err) {
console.log(err);
return Observable.throw(err);
}
search ():Observable<any> {
return this.jsonp.get('http://gturnquist-quoters.cfapps.io/api/random')
.map(resp => resp.json()).catch(this.handleError);
}
}
MusteriTanimlama
import {Component, OnInit} from '#angular/core';
import {GibService} from "./gib.service";
import {MusteriTanimlama} from "./musteritanimlama";
import { Observable } from 'rxjs/Observable';
import any = jasmine.any;
#Component({
selector: 'cosmo-musteritanimlama',
templateUrl: './musteritanimlama.component.html',
styleUrls: ['./musteritanimlama.component.css'],
providers: [GibService]
})
export class MusteritanimlamaComponent {
constructor(private gibservice: GibService) {
}
search () {
this.gibservice.search().subscribe(m=>{
console.log("search");
console.log(m);
});
}
Thank you for answer
You need add the JsonpModule to imports:
#NgModule({
declarations: [
LoginComponent,
AppComponent
],
imports: [
MainModule,
BrowserModule,
FormsModule,
HttpModule,
JsonpModule, // <<<<===
routing,
InMemoryWebApiModule.forRoot(CosmoData)
],
providers: [
appRoutingProviders
],
bootstrap: [AppComponent]
})
export class AppModule { }