18

After upgrading to babel 7.1.5 my tests fail when i'm using import * as.

test.spec.js

import * as Helper from "../../../../src/renderer/modules/Helper";

describe('Testing', () => {
    it('Should import correctly', () => {
        console.log(Helper.test()) // a
        spyOn(Helper, 'test').and.returnValue('b');
    });
});

Helper.js

function test() {
    return 'a'
}

export {test}

ERROR

'Upgrade.spec.js (7:8)', 'a'

Error: <spyOn> : test is not declared writable or has no setter
Usage: spyOn(<object>, <methodName>)
    at <Jasmine>
    at UserContext.it (webpack:///./test/unit/specs/renderer/Upgrade.spec.js?:7:5)
    at <Jasmine>
Peter I
  • 843
  • 1
  • 9
  • 31
  • 1
    Im getting around this at the moment by using "@babel/plugin-transform-modules-commonjs" within .babelrc plugins just for my tests however this is not ideal. – Peter I Nov 15 '18 at 10:35

4 Answers4

14

source: Can webpack 4 modules be configured as to allow Jasmine to spy on their members?

There's spyOnProperty which allows treating a property as read-only by setting the accessType argument to 'get'.

Your setup would then look like

import * as mod from 'my/module';
//...
const funcSpy = jasmine.createSpy('myFunc').and.returnValue('myMockReturnValue');
spyOnProperty(mod, 'myFunc', 'get').and.returnValue(funcSpy);
Xeni
  • 156
  • 2
  • 3
2

I've had the same issue and the only workaround I found was to use babel-plugin-rewire.

Here are the main files:

  • src/index.js
function bar() {
  return 42;
}

export function foo() {
  const result = bar();
  return result;
}
  • test/index_test.js
import { foo, __RewireAPI__ as RewireAPI } from '../src/index';

describe('test foo', () => {
  it('should call bar', () => {
    const barSpy = jasmine.createSpy('bar');
    RewireAPI.__Rewire__('bar', barSpy);
    foo();
    expect(barSpy).toHaveBeenCalledWith();
  });
});
  • karma.conf.js
module.exports = function (config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: ['test/index_test.js'],

    // list of files / patterns to exclude
    exclude: [],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/**/*.js': ['webpack', 'sourcemap'],
    },

    webpack: {
      mode: 'development',
      devtool: 'inline-source-map',
      module: {
        rules: [
          {
            test: /src\/.+\.js$/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: ['@babel/preset-env'],
                plugins: ['rewire'],
              },
            },
          },
        ],
      },
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    // browsers: ['Chrome'],
    browsers: ['MyHeadlessChrome'],

    customLaunchers: {
      MyHeadlessChrome: {
        base: 'ChromeHeadless',
        flags: ['--remote-debugging-port=9333'],
      },
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,
  });
};
  • package.json
{
  "name": "webpack-karma-spy",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "./node_modules/karma/bin/karma start"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/preset-env": "^7.8.4",
    "babel-loader": "^8.0.6",
    "babel-plugin-rewire": "^1.2.0",
    "eslint": "^6.8.0",
    "eslint-config-airbnb-base": "^14.0.0",
    "eslint-plugin-import": "^2.20.1",
    "jasmine": "^3.5.0",
    "karma": "^4.4.1",
    "karma-chrome-launcher": "^3.1.0",
    "karma-jasmine": "^3.1.1",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-webpack": "^4.0.2",
    "webpack": "^4.41.6"
  }
}
Gpack
  • 1,878
  • 3
  • 18
  • 45
0

The easiest way to solve this problem is to create a wrapper around the module you want to import. It seems there is a bug with Jasmine's import system that causes exported functions to fail when spied upon. Here is an example with the nanoid package that will work.

Create a wrapper.

import {nanoid} from "nanoid";

export const idGenerator = {
  create: () => {
    return nanoid();
  },
}

Then in your test spy as normal.

import {idGenerator} from "path-to-id-generator";

// Calling this will override the implementation
spyOn(idGenerator, 'create').and.returnValue('custom-id');
Ash Blue
  • 5,344
  • 5
  • 30
  • 36
0

I did it by this

export const fooFunction = (url: string) => {
  // do somthing
}
// wrap individual functions to class
export abstract class FooWrapper {
  static readonly fooFunction = fooFunction
}

usage

import { FooWrapper } from '../utils';

// change call direct function by
FooWrapper.fooFunction('hello')

testing

const spyFoo = spyOn(FooWrapper, 'fooFunction')
expect(spyFoo).toHaveBeenCalled()
Do Cao Huynh
  • 71
  • 1
  • 1