Jest - sgml/signature GitHub Wiki

Syntax

  • HTML attribute: "data-testid"
  • JavaScript object: getbytestid
  • node cli command: node ./node_modules/jest/bin/jest.js <path-to-your-file>.js

Examples

Command Line

Use the following pattern: npx jest ./tests/myTest.spec.js src/mySource.js

Vue global test

test('Vue global object should have more than one key', () => {
  let keyCount = 0;
  
  for (let key in global.Vue) {
    if (global.Vue.hasOwnProperty(key)) {
      keyCount++;
    }
  }

  expect(keyCount).toBeGreaterThan(1);
})

Vue compiler test

import { mount } from '@vue/test-utils';
import MyComponent from '@/components/MyComponent.vue';

describe('MyComponent', () => {
  it('renders correctly', async () => {
    const wrapper = mount(MyComponent);
    await wrapper.vm.$nextTick();
    expect(wrapper.find('div').text()).toBe('Expected Text');
  });
});

Vue foobar test

Source file

// foo.js
function foo() {
  return true;
}

module.exports = foo;

Test file

// bar.js
const foo = require('./foo');

test('bar', () => {
  expect(foo()).toBe(true);
});

Runner

npx jest ./bar.js

Modulino Test

// foo-bar.js
function foo() {
  return true;
}

function runTests() {
  const result = foo();
  if (result === true) {
    console.log('Test passed');
  } else {
    console.log('Test failed');
  }
}

// Only run tests if this script is executed directly
if (require.main === module) {
  runTests();
}

module.exports = foo;

CoffeeScript

Transformer

// coffeeTransformer.js
const coffee = require('coffeescript');

module.exports = {
  process(src, filename) {
    return coffee.compile(src, { bare: true });
  },
};

jest.config.js for transformer

// jest.config.js
module.exports = {
  transform: {
    '^.+\\.coffee$': 'coffeeTransformer.js',
    '^.+\\.ssi$': 'ssiTransformer.js',
  },
  moduleFileExtensions: ['js', 'jsx', 'coffee', 'ssi'],
};

Test for window or globals

// env-check.js
function checkEnvironment() {
  const env = {
    hasGlobal: typeof global !== 'undefined',
    hasWindow: typeof window !== 'undefined'
  };

  return env;
}

function runTests() {
  let testFramework;
  try {
    // Attempt to require Jest
    testFramework = require('@jest/globals');
  } catch (e) {
    // Fallback to Vitest if Jest is not available
    testFramework = require('vitest');
  }

  const { describe, it, expect } = testFramework;

  describe('Environment Check', () => {
    it('should detect the global object', () => {
      const env = checkEnvironment();
      expect(env.hasGlobal).toBe(true);
    });

    it('should detect the window object', () => {
      const env = checkEnvironment();
      expect(env.hasWindow).toBe(true);
    });
  });
}

if (require.main === module) {
  runTests();
}

module.exports = checkEnvironment;

References