Skip to content

Test‐Packages

TimCi edited this page Nov 6, 2023 · 1 revision

Jest

Nützliche Links / Quellen

Funktionen

  • hauptsächlich Unit-Tests
  • Coverage mit --coverage
  • unterschiedliche keywords zum vergleichen des Erwarteten (z. B. expect().toBe();)
  • Mock-functions (siehe: https://jestjs.io/docs/mock-functions)

Installation

  • schnell benutzbar mit npm install --save-dev jest
  • genauer konfigurierbar mit jest.config.js-File
    • Beispiel von Chat-GPT:
    module.exports = {
        // Modul-Dateien, die getestet werden sollen
    testMatch: ["**/__tests__/**/*.js", "**/?(*.)+(spec|test).js"],
    
    // Verwende den Jest-Runner für JavaScript-Dateien
    transform: {
        "^.+\\.js$": "babel-jest",
    },
    
    // Pfade zu den Test-Dateien
    roots: ["<rootDir>/src"],
    
    // Test-Umgebung
    testEnvironment: "node",
    
    // Reporter für die Testergebnisse
    reporters: ["default"],
    
    // Jest-Konfiguration für Browser-Umgebungen
    testURL: "http://localhost",
    
    // Optionen für die Test-Runner
    verbose: true,
    };
    

Beispiel aus github

Let's get started by writing a test for a hypothetical function that adds two numbers. First, create a sum.js file:

function sum(a, b) {
return a + b;
}
module.exports = sum;

Then, create a file named sum.test.js. This will contain our actual test:

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});

Add the following section to your package.json:

{
    "scripts": {
        "test": "jest"
    }
}

Finally, run npm test and Jest will print this message:

PASS  ./sum.test.js
✓ adds 1 + 2 to equal 3 (5ms)

You just successfully wrote your first test using Jest!

Testthat

Nützliche Links / Quellen

Funktionen

Installation:

# Install the released version from CRAN
install.packages("testthat")

# Or the development version from GitHub:
# install.packages("pak")
pak::pak("r-lib/testthat")

library(testthat)

Beispiel

Let's get started by writing a test for a hypothetical function that adds two numbers:

add_two_numbers <- function(a, b) {
    return(a + b)
}

Then, create a file which name starts with "test" for example "test_addition.R". This will contain our actual test:

test_that("Adding two numbers works", {
    result <- add_two_numbers(2, 3)
    expect_equal(result, 5)
})

Finally, run test_dir(".") and Testthat will print the results

Clone this wiki locally