Code Bug Fix: Vue Jest Test suite failed to run: Unexpected character

Original Source Link

I am using md file in my code as child component. Now when i want to test parent.vue file. I am getting error as code is not able to understand the content in .md file.
What should I do?
Is there any fix to mock md file in jest

sample.spec.js- Test suite failed to run

/Users/Desktop/ui/src/assets/docs/groups.md: Unexpected character '#' (1:0)

  > 1 | # **groups** 
      | ^

Tagged : / /

Code Bug Fix: Jest – output coverage in json format

Original Source Link

I am currently looking to do some analysis of our unit testing and so want to use the jest coverage to do this.

I am currently using version 24.5.0 and my script is jest --config=./test-helpers/jest-config.json --coverage --coverageReporters='json-summary' however this does not seem to output anything at all.

When I run jest --config=./test-helpers/jest-config.json --coverage --coverageReporters='text-summary' however, it outputs the data nicely into text form.

I’ve followed the docs, but can’t seem to work out why it won’t output my data as json.

For reference, this is the jest config file

{
  "setupFilesAfterEnv": [
    "./test-helpers/test-setup.js"
  ],
  "testRegex": "(/src/)(.+)\.test\.js$",
  "rootDir": "../",
  "snapshotSerializers": [
    "enzyme-to-json/serializer"
  ],
  "collectCoverage": true
}

Tagged : /

Code Bug Fix: Getting TimeOut Error while running asynchronous test in jest

Original Source Link

This is the code where i am writing unit test in jest:

import { Connector, DbConnector } from "@custom/connector"; // package contains mongodb operations.

export class DBService {
  private connector: Connector;
  constructor() {
    this.connector = DbConnector.getInstance();
    this.connector.connect();
  }

  public async saveData() {
    return this.connector.update(collName, condition, update, options).then(() => {
       // logger
    });
 }
}

unit test:

import { Connector, DbConnector } from "@custom/connector";
import DBService from "service.ts";

it("success", async () => {

    const db = new DBService ();
    const records = { ok: 1 };
    jest.spyOn(DbConnector, "getInstance").mockImplementation((): any => {
      return {
        connect() { return Promise.resolve(); },
        update() { return Promise.resolve(records); },
      };
    });

    expect(await db.saveData()).resolves.toEqual(records); // Not sure what to do here
  });

When i run, i am getting below error:

Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:

Can somebody help me where i am missing? Any help would be really appreciated.

Thanks in advance.

Here is the unit test solution:

dbService.ts:

import { Connector, DbConnector } from './dbConnector';

export class DBService {
  private connector: Connector;
  constructor() {
    this.connector = DbConnector.getInstance();
    this.connector.connect();
  }

  public async saveData() {
    const collName = 'collName';
    const condition = 'condition';
    const update = {};
    const options = {};
    return this.connector.update(collName, condition, update, options).then((reconds) => {
      return reconds;
    });
  }
}

dbConnector.ts:

export interface Connector {
  connect(): void;
  update(collName, condition, update, options): Promise<any>;
}

export class DbConnector implements Connector {
  public static connector: Connector;
  public static getInstance() {
    if (this.connector) {
      return this.connector;
    }
    this.connector = new DbConnector();
    return this.connector;
  }
  private constructor() {}
  public connect() {
    console.log('connect to db');
  }
  public async update(collName, condition, update, options) {
    return 'real update';
  }
}

dbService.test.ts:

import { DBService } from './dbService';
import { DbConnector } from './dbConnector';

describe('61815803', () => {
  it('should pass', async () => {
    const records = { ok: 1 };
    const dbConnectorMock = {
      connect: jest.fn(),
      update: jest.fn().mockResolvedValueOnce(records),
    };
    jest.spyOn(DbConnector, 'getInstance').mockReturnValueOnce(dbConnectorMock);
    const dbService = new DBService();
    const actual = await dbService.saveData();
    expect(actual).toEqual({ ok: 1 });
    expect(DbConnector.getInstance).toBeCalledTimes(1);
    expect(dbConnectorMock.connect).toBeCalledTimes(1);
    expect(dbConnectorMock.update).toBeCalledWith('collName', 'condition', {}, {});
  });
});

unit test results with coverage report:

 PASS  stackoverflow/61815803/dbService.test.ts (10.698s)
  61815803
    ✓ should pass (6ms)

----------------|---------|----------|---------|---------|-------------------
File            | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------------|---------|----------|---------|---------|-------------------
All files       |      76 |        0 |   55.56 |   73.91 |                   
 dbConnector.ts |      50 |        0 |      20 |   45.45 | 9-13,17,20        
 dbService.ts   |     100 |      100 |     100 |     100 |                   
----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        12.495s

You may want to set the timeout config globally for jestjs like:
jest.setup.js:

jest.setTimeout(10 * 1000);

jest.config.js:

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'node',
  setupFilesAfterEnv: [
    './jest.setup.js',
  ]
}

Tagged : / / / /

Code Bug Fix: how to mock api and inside foreach or map loop in jest?

Original Source Link

sample method
i have javascript method . it have have callback function. how to mock . this method with callback function. and callback returns some data. how to mock that data with foreach loops

let localData = [];
 let usemarks = {};
    this.apiCall('/getuser', { id: 1 }, function (err, response) {
        if (!err && response)
        {
            var data = JSON.parse(response.toString().replace(/'/g, '"'));
            if (data.success)
            {
                data.user.forEach((item)=> {
                    localData.push(item);
                    item.marks.forEach((mark) => {
                        if (user.id == 10) {
                            usemarks = mark;
                        }

                    })
                })
                if (data.user.length > 0) {
                    let user = data.user[0];
                    this.name = User.name;
                    this.Id = user.id;
                    this.loc = user.loc;
                }
            }
        }
    });

Tagged : /

Code Bug Fix: How to write test cases for an object in jest enzyme?

Original Source Link

Can anyone help me writing unit test cases for object in jest react-typescript?

My file name is home.tsx and code is as follows where tableIcons is my object-

export const tableIcons = {
  Add: forwardRef((props: any, ref: any) => <AddBox {...props} {...ref} />),
  Check: forwardRef((props, ref) => <Check {...props} {...ref} />),
}

my home.test.tsx file is as follows –

import AddBox from "@material-ui/icons/AddBox";
import Check from "@material-ui/icons/Check";
import { shallow } from "enzyme";
import React, { forwardRef } from "react";

const tableIcons = {
  Add: forwardRef((props: any, ref: any) => <AddBox {...props} {...ref} />),
};
const tableIcons1 = {
  Add: forwardRef((props: any, ref: any) => <AddBox {...props} {...ref} />),
};

describe("Scenario Utils Component Rendering", () => {
  test("should test Check Component", () => {
    expect(JSON.stringify(tableIcons1)).toEqual(JSON.stringify(tableIcons));
  });
});

My test case is passed in this case but when I check my code coverage then it is still saying statement not covered and function not covered. So how to cover all these statements and functions ?

Tagged : /

Code Bug Fix: not able to exclude asset folder for sonarqube code coverage

Original Source Link

I have added asset folder to exclude the coverage. still I am able to see the bugs of asset folder in sonarqube project.
Any idea what is wrong with my code or sonarqube check for bugs in every folder .
Below is json snippet I have added.

"collectCoverage": true,
"coverageDirectory": "<rootDir>/tests/unit/coverage",
"collectCoverageFrom": [
   "src/**/*.{js,jsx,vue}",
   "!src/assets/**/*"
]

Tagged : / /

Code Bug Fix: Unexpected token, expected “;” jest + enzyme in react native

Original Source Link

I am my first test in react native using jest and this is the error

FAIL tests/app.test.js
● Test suite failed to run

SyntaxError: /Users/joyce/Projects/MamaOpe/mobileapp/node_modules/react-native/Libraries/polyfills/error-guard.js: Unexpected token, expected ";" (14:5)

  12 | let _inGuard = 0;
  13 |
> 14 | type ErrorHandler = (error: mixed, isFatal: boolean) => void;
     |      ^
  15 | type Fn<Args, Return> = (...Args) => Return;
  16 |
  17 | /**

  at Parser._raise (node_modules/@babel/parser/lib/index.js:742:17)
  at Parser.raiseWithData (node_modules/@babel/parser/lib/index.js:735:17)
  at Parser.raise (node_modules/@babel/parser/lib/index.js:729:17)
  at Parser.unexpected (node_modules/@babel/parser/lib/index.js:8779:16)
  at Parser.semicolon (node_modules/@babel/parser/lib/index.js:8761:40)
  at Parser.parseExpressionStatement (node_modules/@babel/parser/lib/index.js:11637:10)
  at Parser.parseStatementContent (node_modules/@babel/parser/lib/index.js:11238:19)
  at Parser.parseStatement (node_modules/@babel/parser/lib/index.js:11104:17)
  at Parser.parseBlockOrModuleBlockBody (node_modules/@babel/parser/lib/index.js:11679:25)
  at Parser.parseBlockBody (node_modules/@babel/parser/lib/index.js:11665:10)

this is my babel.config.js

module.exports = {
 presets: ['@babel/preset-env'],
 plugins: ['@babel/plugin-proposal-class-properties'],
 };

this is my jest.config.js

module.exports = {
 preset: 'react-native',
 moduleFileExtensions: ['js', 'jsx', 'json', 'node'],
 transformIgnorePatterns: [
'node_modules/(?!(jest-)?react-native)',
'node_modules/?!(react-navigation)',
 ],
  };

what am I doing wrong?? the app is built with react native cli not expo

Tagged : /

Code Bug Fix: Vuetify Jest Unknown custom element

Original Source Link

I am writing unit tests for my project, using Jest. Project is based on Vue, Vuetify (1.5) and TypeScript (and vue-property-decorator).

I have basic wrapper for <v-btn>. It looks like this:

<template>
  <v-btn
    :round="!square"
    v-on="$listeners"
  >
    <slot />
  </v-btn>
</template>

<script lang="ts">
import { Vue, Prop, Component } from 'vue-property-decorator';

import { VBtn } from 'vuetify/lib';

@Component({
  components: {
    VBtn,
  },
})
export default class Btn extends Vue {
  @Prop({ default: false, type: Boolean }) private square!: boolean;
}
</script>

And I wrote basic test, just to mount this component:

import { mount } from '@vue/test-utils'
import Vue from 'vue';
import Btn from './Btn.vue';

describe('Btn', () => {

  it('should render button', () => {
    const wrapper = mount(Btn, {
      propsData: {
        onClick: () => {}
      }
    });

    console.log((Vue as any).options.components.VBtn)

    console.log('=======================');
    console.log(wrapper.html());
    console.log('=======================');
  });
});

When running test I’m getting this error:

  console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
    [Vue warn]: Unknown custom element: <v-btn> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

    found in

    ---> <Btn>

But I know that component is registered – it works when running the project (not test). Also, I have console log in test that checks if it is registered (console.log((Vue as any).options.components.VBtn)) and it shows that component is registered globally.

Here is my jest.config.js:

module.exports = {
  moduleFileExtensions: [
    "js",
    "ts",
    "json",
    "vue"
  ],
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
    "^vuetify/lib$": "vuetify",
  },
  modulePaths: [
    "<rootDir>/src",
    "<rootDir>/node_modules"
  ],
  transform: {
    ".+\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub",
    "^.+\.ts?$": "ts-jest",
    ".*\.(vue)$": "vue-jest",
  },
  transformIgnorePatterns: [
    "<rootDir>/node_modules/(?!(vuetify)/)",
  ],
  testRegex: "(/__tests__/.*|(\.|/)(test|spec))\.(js?|ts?)$",
  setupFilesAfterEnv: ['<rootDir>/tests/unit/setup.ts'],
}

And setup.ts file:

import Vue from 'vue';
import Vuetify from 'vuetify';

Vue.config.productionTip = false;
Vue.use(Vuetify);

I was trying to move code from setup.ts to the test but it doesn’t changed anything. I think there may be problem with 'vue-property-decorator' but my whole project is based on it so I don’t want to change it.
Can you help me? Maybe something is wrong in my Jest transform configuration?

I managed to solve this problem. Had to change two lines of code:

In my Btn component, changed VBtn import to:
import { VBtn } from 'vuetify/lib/components/VBtn'; (imported from vuetify/lib/components/VBtn, not from vuetify/lib).

In jest.config.js update in moduleNameMapper to 'vuetify/lib(.*)': '<rootDir>/node_modules/vuetify/es5$1'.

And that is all, now it works 🙂

My whole jest.config.js:

module.exports = {
  moduleFileExtensions: [
    "js",
    "ts",
    "json",
    "vue"
  ],
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
    'vuetify/lib(.*)': '<rootDir>/node_modules/vuetify/es5$1',
  },
  modulePaths: [
    "<rootDir>/src",
    "<rootDir>/node_modules"
  ],
  transform: {
    ".+\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub",
    "^.+\.ts?$": "ts-jest",
    ".*\.(vue)$": "vue-jest",
  },
  transformIgnorePatterns: [
    "<rootDir>/node_modules/(?!(vuetify)/)",
  ],
  testRegex: "(/__tests__/.*|(\.|/)(test|spec))\.(js?|ts?)$",
  setupFilesAfterEnv: ['<rootDir>/tests/unit/setup.ts'],
}

Tagged : / / / /

Code Bug Fix: Mock requestAnimationFrame in Jest

Original Source Link

I have the following code in my web app:

  const scroll = () => {
    const scrollPerTick = (amountToScroll / 200) * 12;
      if (scrolled < amountToScroll) {
        container.scrollBy(0, scrollPerTick);
      }
    window.requestAnimationFrame(() => scroll(scrollBy));
  };

if (scrolled < amountToScroll) {
    window.requestAnimationFrame(scroll);
}

When I run Jest, this code is not covered because requestAnimationFrame is not executed by Jest, though it doesn’t throw any error. I tried mocking requestAnimationFrame by putting following code in my test file, as described here:

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',
};
global.requestAnimationFrame = function (callback) {
  return setTimeout(callback, 0);
};
global.cancelAnimationFrame = function (id) {
  clearTimeout(id);
};
copyProps(window, global);

But it didn’t work. Is there any way to mock requestanimationFrame in my tests?

Tagged : /

Code Bug Fix: Try to do a unit test in TypeScript

Original Source Link

I’m trying to understand how unit tests work

I’ve got this method:

public async parseTest(diffComponents: any[]): Promise<Map<string, string[]>> {
    const result: Map<string, string[]> = new Map();
    for (let i = 0; i < diff.length; i++) {
        const element = diff[i];
        try {
            const fileContent = fs.readFileSync("changelog.txt","UTF-8");
            const lines = fileContent.split("n");
            const list = this.retrieve(lines, element);
            result.set(element.components, list);
        } catch (err) {
            return Promise.reject("ERROR: Cannot find file from components");
        }
    }
    return result;
}

The ouput of result is for example:

Map { 'toto' => [ 'toto-11' ] }

And here this is my test but it doesn’t work:

describe("parse", () => {
    test("check map result", () => {
        // Given
        const array = [{ components: "toto", newVersion: "2.2", oldVersion: "2.1" }];

        // When
        const result = new ChangelogService().parseTest(array);
        const expected = new Map();
        expected.set("toto", "toto-11");
        // Then
        expect(result).toBe(expected);   // problem in this line 
    });
});

the error of the line is :

Error: expect(received).toBe(expected) // Object.is equality
Expected: Map {"toto" => "toto-11"}
Received: {}Jest

Can you explain the problem or give a better test method?

.toBe does exact match, it means it has to be the same object.

if you want compare that objects contain the same key and values you need to use .toEqual.

Also you Map is an array, you should do the same in the expected.

And the method returns promise you need to solve.

describe("parse", () => {
    test("check map result", async () => { // <- add async
        // Given
        const array = [{ components: "toto", newVersion: "2.2", oldVersion: "2.1" }];

        // When
        const result = await (new ChangelogService().parseTest(array)); // <- add await
        const expected = new Map();
        expected.set("toto", ["toto-11"]); // <- wrap the value
        // Then
        expect(result).toEqual(expected); // <- change to toEqual
    });
});

Then jasmine will go through the result and check it key by key with expected.

Tagged : / / /