TypeScript UnitTests on Module - unit-testing

I want to run unit tests in typescript. I have a simple folder structure where directory app contains an app.ts like following
export module app {
export class Config {
testMe() {
return "Hallo";
}
}
}
The unit tests that lies in directory test:
import app = require('../app/conf');
import * as chai from 'chai';
var config = new app.app.Config();
chai.expect(config.testMe()).to.equals("Hallo");
As TypeScripts documentation states in http://www.typescriptlang.org/Handbook#modules-pitfalls-of-modules when TypeScript code is used as an external module it does not make sense to use the module concept at all.
As you can see app.app.Config is not a very elegant way.
I can only run my unit tests on compiled TypeScript code. So I can only use modules if I don't care about unit tests or is there a simpler way?

Have app.ts:
export class Config {
testMe() {
return "Hallo";
}
}
and test.ts:
import app = require('../app/conf');
import * as chai from 'chai';
var config = new app.Config();
chai.expect(config.testMe()).to.equals("Hallo");
And if your original code worked, so will this. No more app.app and no more needless internal modules.

Related

Unit testing a non-class Groovy function using Gradle

I was given a Jenkins Library project, and I'd like to write some unit tests for it. I'm currently using the Jenkins Pipeline Shared Libraries Gradle Plugin which sets up source paths for unit and integration tests.
The source file I want to test is located at src/org/example/pipeline/Terraform.groovy and looks like:
package org.example.pipeline
def terraformNewWorkspace(String env, Map config) {
def tfWSCreate = """
#!/bin/bash
set -e
terraform workspace new ${env} || true
terraform workspace select ${env}
terraform workspace list
"""
if (config.currentWorkingDirectory != null) {
dir("${config.currentWorkingDirectory}") {
sh(returnStatus: false, script: tfWSCreate)
}
} else {
sh(returnStatus: false, script: tfWSCreate)
}
}
and I've created a test/unit/groovy/example/PipelineTests.groovy which looks like the following:
import static org.example.pipeline.Terraform.terraformNewWorkspace as terraformNewWorkspace
class TerraformUnitTests extends GroovyTestCase {
void testNewWorkspace() {
terraformNewWorkspace("dev", [currentWorkingDirectory: "/tmp/test"])
}
}
However I get a groovy.lang.MissingMethodException at PipelineTests.groovy when I try to execute this using gradle test. I've also tried the following as some documentation seems to indicate functions that are not part of a class get added in Groovy to a class with the name of the file, but I get the same exception about a missing method.
import org.example.pipeline.Terraform
...
t = new Terraform()
t.terraformNewWorkspace("dev", [currentWorkingDirectory: "/tmp/test"])
What is the correct way to import and test this individual function using gradle/groovy?
It was a simple syntax error. I forgot to use def for my variable:
import org.example.pipeline.Terraform
class TerraformUnitTests extends GroovyTestCase {
void testNewWorkspace() {
def t = new Terraform()
t.terraformNewWorkspace("dev", [currentWorkingDirectory: "/tmp/test"])
}
}

Is there a way to use global jest mocks with Quasar?

I want to mock my i18n object globally.
I'm following a guideline. I'm creating jest.init.ts file inside my jest folder. It contains following rules:
import { config } from "#vue/test-utils"
config.mocks["$t"] = () => ""
But my tests fail with the error:
TypeError: _vm.$t is not a function
I've also tried to import quasar implementation of vue-test utils ('#quasar/quasar-app-extension-testing-unit-jest'), but the result is the same
I found this https://testing.quasar.dev/packages/unit-jest/. Here is a section for mocking i18n.

How to mock global Vue.js variable in JEST test

I have a global property/variable with my app urls:
Vue.prototype.$apiUrls = {
root: 'http://localhost:8080/',
api: 'api/v1/'
// etc.
}
I use it inside my components as axios request:
axios.get(`${this.$apiUrls.root}${this.$apiUrls.api}/users/`)
Now I want to test my component's code, I've mocked axios already, but still I receive an error:
TypeError: Cannot read property '$apiUrls' of undefined
I've tried to define/mock this property inside each test and/or in JEST's setup file, like e.g.
global.$apiUrls = {...}
// or
Vue.prototype.$apiUrls = {...}
// or
Object.defineProperties(Vue.prototype, {$apiUrls: {...}})
I've also tried mocking it to window or this (yeah, thats silly), but with no success - I still receive that error - please help.
There is two ways to achieve this. One is using the Config option, as mentioned by #Aldarund. You can read about it here.
If you are using Jest, I recommend doing this in the jest.init.js file:
import { config } from '#vue/test-utils'
config.mocks['$apiUrls'] = {
'some/endpoint'
}
Then add this to the jest section of your package.json:
"setupFiles": [
"<rootDir>/jest.init.js"
]
Now it is globally mocked. If you want to do this on a per test basis, you can use the mocks mounting option:
const wrapper = shallowMount(Foo, {
mocks: {
$apiUrls: 'some/endpoint'
}
})
Hopefully this helps!
If you are interested I am compiling a collection of simple guides on how to test Vue components here. It's under development, but feel free to ask make an issue if you need help with other related things to testing Vue components.
I don't think the answers above work anymore (in 2020).
Here's what worked for me:
For vue-test-utils 1.x.x (Vue 2)
Create a new file, name it eg. jest.init.js
Give it the following content:
import { config } from "#vue/test-utils";
config.mocks["yourGlobalProperty"] = label => label; //you can replace it with your own mock
Add this to your jest.config.js (actually write "rootDir", don't replace anything with a real path)
module.exports = {
setupFiles: ["<rootDir>/jest.init.js"]
}
These files will be only ran before jest runs unit tests.
Note that I'm importing {config}, not the default export. I don't know why the default didn't work for me. Even the documentation for vue test utils doesn't import the default export anymore
Also make sure you're not trying to import from the old vue-test-utils package. (The new one is #vue/test-utils)
For #vue/test-utils 2.x.x (vue-test-utils-next) (Vue 3)
Follow steps like for 1.x.x above, but in step two, do this instead:
import { config } from "#vue/test-utils"; //2.0.0-beta.5
config.global.mocks = {
yourGlobalProperty: label => label
};
You can do it with vue-test-utils beta 15 and later.
Here docs
And some example would be:
import VueTestUtils from '#vue/test-utils'
VueTestUtils.config.mocks['$apiUrls'] = {
...
}

Jest globalSetup option not working

I'm trying to make a function called loadFixtures available to all Jest tests.
I have the following line within the jest config object inside package.json:
"globalSetup": "<rootDir>/src/test/js/config/setup-globals.js"
setup-globals.js contains:
module.exports = function() {
function loadFixtures(filename) {
console.info('loadFixtures is working');
}
}
Within my tests I have, for example:
beforeEach(() => {
loadFixtures('tooltip-fixture.html');
});
However when I run Jest I get the following for each test:
ReferenceError: loadFixtures is not defined
I verified that the setup-globals.js file is definitely being found and loaded in by Jest before the tests execute.
Can anyone assist in identifying where I've gone wrong here? I've spent pretty much an entire day trying to debug without luck.
You should be using setupFiles and not globalSetup.
// jest config
"setupFiles": [
"<rootDir>/src/test/js/config/setup-globals.js"
]
then src/test/js/config/setup-globals.js:
global.loadFixtures(filename) {
console.info('loadFixtures is working');
}
references: https://medium.com/#justintulk/how-to-mock-an-external-library-in-jest-140ac7b210c2
If you bootstrapped your application using npx create-react-app (CRA), you do not need to add the setupFiles key under your jest key in the package.json file (CRA prevents overriding that key).
what you simply need to do is to add the file setupTests.js in the root of your SRC folder, and populate it with the snippet below:
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({
adapter: new Adapter(),
});
remember you must have earlier installed the right versions of enzyme and enzyme-adapter-react
CRA has been wired to automatically load the setupTests.js file in the src folder if it exists. Hence after adding these, you can then go over to your test and do import {shallow} from enzyme without triggering an error.
if you are not using Create-react-app, all you need to do, in addition to adding the file above to your src folder is to add the key setupFiles into the jest key in your package.json. it should look like this:
"jest": {
"setupFiles": ['<rootDir>/src/setupTests.js'],
}
and you are good to go.
Cheers!
You're defining a function in a different scope. How about you create a separate module and import it directly in your test files. Or if you really want to define it in the global scope, try using the following code in your setup-globals.js file.
module.exports = function() {
global.loadFixtures = function(filename) {
console.info('loadFixtures is working');
}
}

How to add unittest for Kotlin code in the same file and run it?

I have some code like this:
class Solution {
fun strStr(haystack: String, needle: String): Int {
return haystack.indexOf(needle)
}
}
In Python normally I can add some tests in the same file and add something like:
<some tests above here>
if __name__ == '__main__':
unittest.main()
To run the unit tests. How do I achieve the same thing in Kotlin ?
The reason why tests are normally put into a separate module in Kotlin/Java projects is that, usually, tests need some additional dependencies that do not make sense for production code, like JUnit or other libraries. Also, a test written in the same file would be compiled into a class that is a part of the production code output.
In a project that is published and used as a dependency for other projects, consider not mixing production and test code.
You can, of course, add those test dependencies to the production code. As an example for JUnit, add the dependency (in a Gradle project: dependencies { compile 'junit:junit:4.12' }, in an IntelliJ project: see the reference), then just add a testing class with a #Test function:
import org.junit.Test
import org.junit.Assert
class Solution {
fun strStr(haystack: String, needle: String): Int {
return haystack.indexOf(needle)
}
}
class SolutionTest {
#Test
fun testSolution() {
val text = "hayhayhayneedlehayhay"
val pattern = "needle"
val result = strStr(text, pattern)
Assert.assertEquals(8, result)
}
}