我创建了一个库mylib
,该库已通过以下webpack部分进行了编译:
output: {
...
library: 'mylib',
libraryTarget: "var",
libraryExport: 'default',
},
,以便可以将其包含在脚本标签中并直接使用,例如:
<script src="mylib.js"></script>
<script>
mylib.foo(); // the name mylib is available
</script>
在一个新应用中,我想基于mylib
(./src/point.js
):
export class Point extends mylib.Widget {
constructor(x, y) {
super();
this.x = x;
this.y = y;
}
}
并使用jest
编写单元测试(./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);
});
当然jest
抱怨说自己不知道mylib
是什么:
(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.
我对webpack / babel / jest配置有点不知所措,这只是我第二次使用jest(第一次是在mylib
上运行的很好)。如何使它工作?
答案 0 :(得分:1)
由于您希望在环境中将mylib
定义为全局变量,因此可以创建一个安装文件并将其添加到jest配置的setupFilesAfterEnv
package.json
"jest": {
// ....
"setupFilesAfterEnv": ['<rootDir>/jest.setup.mylib.js']
}
jest.setup.mylib.js
// define global variable
global.mylib = jest.genMockFromModule('./src/mylib.js');
或在测试中定义
test-point.js
import {Point} from "../point";
beforeAll(() => {
global.mylib = jest.genMockFromModule('./src/mylib.js');
});
但是,如果您已将mylib
添加为依赖项,并且已require
将其添加到您的观点中
point.js
const mylib = require('mylib');
那么您就可以在测试中自动模拟它
test-point.js
import {Point} from "../point";
jest.mock('mylib');
test("test-point", () => {
// ....