技术解析

Jest 写 unit test,如何 mock 同一个文件中被调用的函数?
0
2021-08-16 19:53:40
idczone

JavaScript/TypeScript, 使用 Jest 写 unit test 。

一个文件里面有两函数

function a() {
  //调用了其它 modules/files 里面的类或者函数
}

function b() {
  a();
}

现在我用 Jest 测试 b,我想把 a mock 掉,请问有没有比较好的方法?

谢谢!


如果 a 和 b 的定位都是公有方法,那么可以模块化把 a, 和 b 都倒出,测 b 的时候把 a Mock 掉。
如果 a 的定位是私有方法,那么一般不用 Mock a,也不用专门给 a 写测试。单元测试的最小单位不一定是一个函数,可以是一个小模块,甚至一个类。

```js
function a() {
//调用了其它 modules/files 里面的类或者函数
}
a = jest.fn()
function b() {
a();
}
expect(a).toBeCalled()
```
https://jestjs.io/docs/en/mock-functions.html

兄弟,没有这么简单吧。你这是 test 代码和 prod 代码在同一文件内么?
xxx.js
```javascript
function a() {
//调用了其它 modules/files 里面的类或者函数
}
function b() {
a();
}
```

xxx.test.js
```
import {a, b} from "./xxx.js";

a = jest.fn();
```
这里是会报错的,"can't assign to a because it is not a variable".

https://jestjs.io/docs/en/manual-mocks

https://stackoverflow.com/questions/45111198/how-to-mock-functions-in-the-same-module-using-jest

我觉得 John-Philip 的第一种方法优雅一点。

我觉得没有 export 的内部方法不用直接测,没有 export 说明他只在文件内部有使用,通过测 export 的函数就可以覆盖到内部函数。
问题在于你为什么要 mock a 。如果是想通过 mock a 的返回值来覆盖 b 的分支,那么你应该用不同的 b 参数以及 mock 掉的外部调用的返回来控制 a 的返回值。

数据地带为您的网站提供全球顶级IDC资源
在线咨询
专属客服