Search code examples
jqueryunit-testingtypescriptbrowserifyava

How use AVA with JQuery in Typescript?


I try to test a lib with JQuery but I have an error.

Example :

import { test } from 'ava'
import $ from 'jquery'
import {fixture} from 'ava-browser-fixture'

test.beforeEach('setup fixture',
    fixture("./src/__test__/html/test.html")
);

test("Test JQuery", t => {
    $(t.context.document).ready(function () { // <=== ERROR with yarn test
        $('#test').append("test")
    });
});

Config.json

  "ava": {
    "source": [
      ...
   ],
    "require": [
      "babel-register",
      "ava-browser-fixture"
    ],
    "babel": "inherit"
  }

Error : jquery_1.default is not a function

Have you an idea to resolve this error ?

Thanks

====== Details

You can test my config with the project "typescript-starter". It is a typescript boilerplate for building javascript libraries and projects. Error is with the command "yarn test".

Here the tsconfig.json (here with es5 in target and lib... but same result with es6) :

{
  "extends": "./config/tsconfig.flexible", 
  "compilerOptions": {
    "target": "es5",
    "outDir": "build/main",
    "rootDir": "src",
    "moduleResolution": "node",
    "module": "commonjs",
    "declaration": true,
    "importHelpers": true,
    "inlineSourceMap": true,
    "listFiles": false,
    "traceResolution": false,
    "pretty": true,
    "lib" : [
      "es5",
      "DOM"
    ],
    "types" : [
      "node"
    ],
    "baseUrl": ".", // required for "paths"
    "paths": {
      "sgvizler2": ["src/index.ts"] // write tests without relative paths
    }
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules/**"
  ],
  "compileOnSave": false
}

Solution

  • I found my answer here : https://github.com/rollup/rollup/issues/1267

    The answer is not trivial :

    import { test } from 'ava'
    import {fixture} from 'ava-browser-fixture'
    
    import * as jqueryProxy from 'jquery'
    const jquery: JQueryStatic = (<any>jqueryProxy).default || jqueryProxy
    
    test.beforeEach('setup fixture',
        fixture("./src/__test__/html/test.html")
    );
    
    test("Test JQuery", t => {
        jqueryProxy(t.context.document).ready(function () {
            jqueryProxy('#test').append("test")
        });
    });
    

    Bye