Reputation: 27360
I've created a library mylib
that is compiled with the following webpack section:
output: {
...
library: 'mylib',
libraryTarget: "var",
libraryExport: 'default',
},
so that it can be included with a script tag and used directly, e.g.:
<script src="mylib.js"></script>
<script>
mylib.foo(); // the name mylib is available
</script>
In a new app I would like to build on mylib
(./src/point.js
):
export class Point extends mylib.Widget {
constructor(x, y) {
super();
this.x = x;
this.y = y;
}
}
and use jest
to write unit tests (./src/__tests__/test-point.js
):
import {Point} from "../point";
test("test-point", () => {
const p = new Point(5, 10);
expect(p.x).toBe(5);
expect(p.y).toBe(10);
});
of course jest
complains that it doesn't know what mylib
is:
(dev) go|c:\srv\lib\dkface> jest
FAIL src/__tests__/test-point.js
● Test suite failed to run
ReferenceError: mylib is not defined
1 |
> 2 | export class Point extends mylib.Widget {
| ^
3 | constructor(x, y) {
4 | super();
5 | this.x = x;
at Object.mylib (src/point.js:2:28)
at Object.<anonymous> (src/__tests__/test-point.js:2:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 4.313s
Ran all test suites.
I'm a bit overwhelmed by the webpack/babel/jest configurations and this is only my second time using jest (the first was on mylib
where it works great). How do I get this to work?
Upvotes: 1
Views: 103
Reputation: 32148
As you're expecting mylib
to be defined as global variable in your environment you can create a setup file and add it into your jest configuration's setupFilesAfterEnv
package.json
"jest": {
// ....
"setupFilesAfterEnv": ['<rootDir>/jest.setup.mylib.js']
}
jest.setup.mylib.js
// define global variable
global.mylib = jest.genMockFromModule('./src/mylib.js');
Or define it within your test
test-point.js
import {Point} from "../point";
beforeAll(() => {
global.mylib = jest.genMockFromModule('./src/mylib.js');
});
But if you have added mylib
as a dependency and you have require
d it into your point
point.js
const mylib = require('mylib');
then you'll be able to auto mock it within your test
test-point.js
import {Point} from "../point";
jest.mock('mylib');
test("test-point", () => {
// ....
Upvotes: 1