I am new to JavaScript unit testing. I am trying to test typescript classes and my tests are also written in typescript, which somewhat looks like below:
/// <reference path="../../typings/qunit/qunit.d.ts" />
import Utility1 = require("../utility");//This is script I want to test.
test("utility_test",function() {
...
var result = ...;
var expected = ...;
equal(result, expected, "Test failed");
})
I am using VS 2015 with chutzpah test adapter installed as shown here. To be clear I have installed this to extension to vs 2015: Chutzpah Test Runner Context Menu Extension, and Chutzpah Test Adapter for the Test Explorer and also added Chutzpah NuGet package.
Yet when I build my project, the test doesn't appear in the Test Explorer. And when I tried to run the test from context menu, it fails with this error: Error: Error: Called start() outside of a test context while already started.
Can anyone please let me know where I am going wrong?
EDIT
For the one looking for the solution with require.js, this here worked for me. Now my Chutzpah.json looks like below:
{
"Framework": "qunit",
"CodeCoverageExcludes": [ "*/require.config.js" ],
"TestHarnessReferenceMode": "AMD",
"TestHarnessLocationMode": "SettingsFileAdjacent",
"TypeScriptModuleKind": "AMD",
"AMDBaseUrl": "",
"EnableTestFileBatching": true,
"Compile": {
"Mode": "External",
"Extensions": [ ".ts" ],
"ExtensionsWithNoOutput": [ ".d.ts" ]
},
"References": [
{ "Path": "require.js" },
{ "Path": "require.config.js" },
],
"Tests": [
{ "Path": "jsTests" }
]
}
Chutzpah no longer bundles the Typescript compiler inside of it (as of version 4). You must tell Chutzpah where to find your generated .js files (or/and how to compile them if you want it to).
See the documentation for the Compile setting
as well as these code samples.
Most people will use the external compile mode when working with Visual Studio since VS can compile the .ts files for you and you just need to tell Chutzpah where to find them. That will look like this:
{
"Compile": {
"Mode": "External",
"Extensions": [".ts"],
"ExtensionsWithNoOutput": [".d.ts"]
},
"References": [
{"Includes": ["*/src/*.ts"], "Excludes": ["*/src/*.d.ts"] }
],
"Tests": [
{ "Includes": ["*/test/*.ts"], "Excludes": ["*/test/*.d.ts"] }
]
}
Related
I have been trying this for a while now, without success.
I have an expo app and I am using cypress to test some use cases using the web version of the app (generated by expo).
However, I would like to generate some code coverage as well. I have read the official documentation for it, that recommends to babel-plugin-istanbul do to so, but it does not seem to work with expo.
I am not sure why this would not work.
Edit
I removed the files previously pointed here as they were not important.
Thanks for a wonderful documentation provided by a hero without a cape, I figured that my settings were wrong.
All I needed to do was:
install babel-plugin-istanbul
Update babel.config.js
module.exports = {
presets: ['babel-preset-expo'],
plugins: [
'istanbul',
[
'module-resolver',
{
root: ['.'],
extensions: [
'.js',
],
alias: {
'#': './',
},
},
],
],
};
update cypress/support/index.js
import '#cypress/code-coverage/support';
update cypress/plugins/index.js
module.exports = (on, config) => {
require('#cypress/code-coverage/task')(on, config);
// add other tasks to be registered here
// IMPORTANT to return the config object
// with the any changed environment variables
return config;
};
and voilĂ !
I have the following file: deposit-form.js.
With the following code:
new Vue({
el: '#app',
data: {
title: 'title',
depositForm: {
chosenMethod: 'online',
payMethods: [
{ text: 'Already paid via Venmo', value: 'venmo' },
{ text: 'Pay online', value: 'online' },
{ text: 'In-person payment', value: 'person' }
],
},
},
methods: {
submitDeposit: function() {
$.ajax({
url: 'http://localhost:8000/api/v1/deposit/',
type:'post',
data: $('#deposit-form').serialize(),
success: function() {
$('#content').fadeOut('slow', function() {
// Animation complete.
$('#msg-success').addClass('d-block');
});
},
error: function(e) {
console.log(e.responseText);
},
});
},
showFileName: function(event) {
var fileData = event.target.files[0];
var fileName = fileData.name;
$('#file-name').text('selected file: ' + fileName);
},
},
});
I'm having problems on how to setup Jest, how to import the VueJs functions inside 'methods' to make the tests with Jest.
How should be my code on the deposit-form.test.js ?
The first thing you need to do is export Vue app instance.
// deposit-form.js
import Vue from 'vue/dist/vue.common';
export default new Vue({
el: '#app',
data: {...},
...
});
Now you can use this code in your spec file. But now you need to have #app element before running tests. This can be done using the jest setup file. I will explain why it's needed. When you import your main file (deposit-form.js) into a test, an instance of Vue is created in your main file with new. Vue is trying to mount the application into #app element. But this element is not in your DOM. That is why you need to add this element just before running the tests.
In this file you also can import jQuery globally to use it in your tests without import separately.
// jest-env.js
import $ from 'jquery';
global.$ = $;
global.jQuery = $;
const mainAppElement = document.createElement('div');
mainAppElement.id = 'app';
document.body.appendChild(mainAppElement);
Jest setup file must be specified in the jest configuration section in package.json.
// package.json
{
...,
"dependencies": {
"jquery": "^3.3.1",
"vue": "^2.6.7"
},
"devDependencies": {
"#babel/core": "^7.0.0",
"#babel/plugin-transform-modules-commonjs": "^7.2.0",
"#babel/preset-env": "^7.3.4",
"#vue/test-utils": "^1.0.0-beta.29",
"babel-core": "^7.0.0-bridge.0",
"babel-jest": "^24.1.0",
"babel-loader": "^8.0.5",
"babel-preset-vue": "^2.0.2",
"jest": "^24.1.0",
"vue-jest": "^3.0.3",
"vue-template-compiler": "^2.6.7",
"webpack": "^4.29.5",
"webpack-cli": "^3.2.3"
},
"scripts": {
"test": "./node_modules/.bin/jest --passWithNoTests",
"dev": "webpack --mode development --module-bind js=babel-loader",
"build": "webpack --mode production --module-bind js=babel-loader"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest",
".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
},
"setupFiles": [
"<rootDir>/jest-env.js"
]
}
}
Also, you probably need to configure Babel to use the features of ES6 in your projects and tests. This is not necessary if you follow the commonjs-style in your code. Basic .babelrc file contains next code:
// .babelrc
{
"presets": [
[
"#babel/preset-env",
{
"useBuiltIns": "entry",
"targets": {
"browsers": [
"last 2 versions"
]
}
}
],
"vue",
],
"plugins": [
"#babel/plugin-transform-modules-commonjs",
]
}
Now you can write your tests.
// deposit-form.test.js
import App from './deposit-form';
describe('Vue test sample.', () => {
afterEach(() => {
const mainElement = document.getElementById('app');
if (mainElement) {
mainElement.innerHTML = '';
}
});
it('Should mount to DOM.', () => {
// Next line is bad practice =)
expect(App._isMounted).toBeTruthy();
// You have access to your methods
App.submitDeposit();
});
});
My recommendation is to learn Vue Test Utils Guides and start to divide your code into components. With the current approach, you lose all the power of components and the ability to test vue-applications.
I updated my answer a bit. As I understood from the comment to the answer, you connect the libraries on the page as separate files. Here is my mistake. I didn't ask if the build system is being used. Code in my examples is written in the ECMA-2015 standard. But, unfortunately, browsers do not fully support it. You need an transpiler that converts our files into a format that is understandable for browsers. It sounds hard. But it's not a problem. I updated the contents of the file package.json in response. Now it only remains to create an input file for the assembly and run the assembly itself.
The input file is simple.
// index.js
import './deposit-form';
The build is started with the following commands from terminal.
# for development mode
$ yarn run dev
# or
$ npm run dev
# for production mode
$ yarn run build
# or
$ npm run build
The output file will be placed in the directory ./dist/. Now instead of separate files you need to connect only one. It contains all the necessary for the library and your code.
I used webpack to build. More information about it can be found in the documentation. Good example you can find in this article.
For every element that I have defined in a Polymer 2.x project I get the following warning:
Multiple global declarations of class with identifier Polymer.Element
The build ultimately fails with a Promise rejection at ...\node_modules\polymer-build\lib\analyzer.js
Are these components improperly defined?
How can I properly build the project?
My polymer.json file is
{
"entrypoint": "index.html",
"shell": "src/shop-app.html",
"fragments": [
"src/lazy-resources.html"
],
"sources": [
"src/**/*",
"data/**/*",
"images/**/*",
"app.yaml",
"bower.json",
"manifest.json",
"sw-precache-config.js",
"Web.config"
],
"extraDependencies": [
"manifest.json",
"bower_components/webcomponentsjs/webcomponents-lite.js"
],
"lint": {
"rules": ["polymer-2-hybrid"]
},
"builds": [{
"js": {"minify": true},
"css": {"minify": true},
"html": {"minify": true}
}]
}
This error means that you load the same dependency from two different urls. For instance
myStuff/myApp.html
myOtherStuff/myApp.html
I had the same warning while building my Polymer 2 app. Probably because some of my elements import the same other elements and all of them extend Polymer.Element. I have checked all my elements for duplicate imports. Maybe some third party elements have duplicates, but my elements didn't.
So I added the warning to the ignore list in polymer.json:
{
"lint": {
"rules": [
"polymer-2"
],
"ignoreWarnings": ["multiple-global-declarations"]
},
...
}
I too had same warning and it was gone after cleaning bower_components and node_modules.
I am trying to import the data from a .json file in a .tsx using following:
import data from "data/mockup.json"
but I got the error
Cannot find module 'data/mockup.json'
My webpack config looks like this:
const babelLoader = {
loader: 'babel-loader',
options: {
cacheDirectory: true,
presets: [
["#babel/preset-env", {
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
},
"modules": true
}]
]
}
};
module.exports = {
entry: {...},
resolve: {
extensions: ['.ts', '.tsx', '.js', '.json'],
alias: {
data: path.resolve(__dirname, 'src/app/data')
}
},
output: {...},
module: {
rules: [
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
babelLoader,
{
loader: 'ts-loader'
}
]
},
{
test: /\.js$/,
exclude: /node_modules\/(?!(dom7|swiper)\/).*/,
use: [
babelLoader
]
}
]
},
...
}
enter code here
I think the .json is built in webpack4 by default so there may be something wrong with my webpack config?
Version used:
webpack: v4.4.1
typescript: 2.7.2
declare module in d.ts file
declare module "*.json"
Add a field in tsconfig.json in compiler options
"typeRoots": [ "node_modules/#types", "./typings.d.ts" ],
Now import into file (.tsx)
import * as data from "./dat/data.json";
Webpack#4.4.1 and Typescript#2.7.2
Hope this helps!!!
Ref1: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html
Ref2: https://github.com/Microsoft/TypeScript-React-Starter/issues/12
Although answers are helpful to load the JSON file as a module, they are limited in many aspects
First: the typescript can load by default JSON files, you only need to add into tsconfig.json below line:
{
...
"resolveJsonModule": true,
...
}
second: the suggested solution will enable implicitly for type check and auto-completion
P.S. the attached image is from a tutorial that talks about the same subject click here to check more
Personnaly, uncommenting :
"allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */,
in the file tsconfig.json did the trick.
I found the hint here.
I have an asp.Net Core application with AngularJS code with the following task in gulpfile.js:
gulp.task("concat_app:js", function () {
return gulp.src(js_app, { base: 'wwwroot/' })
.pipe(sourcemaps.init({
loadMaps: true,
identityMap: true,
largeFile: true
}))
.pipe(concat(paths.js_app_dest))
.pipe(sourcemaps.write('.', {
includeContent: false,
mapSources: function (sourcePath, file) {
return '../' + sourcePath;
}
}))
.pipe(gulp.dest("."));
});
If I try to debug in chrome everything is working fine and also my folder structure is correct:
structure in chrome developer tools
But when I try to debug in Visual Studio 2017, it seems not to be correctly mapped, because when I set a breakpoint, it appears in other files. I have tried the same using a tsconfig.json:
{
"compileOnSave": true,
"compilerOptions": {
"allowJs": true,
"sourceMap": true,
"target": "es5",
"jsx": "react",
"outFile": "wwwroot/js/app.js"
},
"include": [
"wwwroot/ngApp/*.js",
"wwwroot/ngApp/**/*.js"
],
"exclude": []
}
This generates a mapfile like this:
{
"version": 3,
"file": "app.js",
"sourceRoot": "",
"sources": [ "../ngApp/_app.js", "../ngApp/_config/appConfig.js" "..." ],
"names": [],
"mappings": "AAAA,CAAC;IACG,YAAY,..."
}
Here also it seems to be mapped somehow wrong, I set a breakpoint, it appears somewhere else. Also my webapplication is stopped, but I can't continue in Visual Studio.
I would prefer to use gulp-sourcemaps, but I had a hard time setting the right directory. Can this be a part of the problem, because my gulpfile.js is not located in the wwwroot-folder? project in visual studio
EDIT: It seems when using tsconfig the breakpoint is always set in the first file (_app.js). What am I missing here?