[英]How to spy on a fakerjs method call
Faker.js allow you to easily create faked data using for example the following: Faker.js允许您使用例如以下内容轻松创建伪造的数据:
import * as faker from 'faker'
console.log(faker.lorem.text())
So I tried to mock this library to spy the use of faker.lorem.text()
:所以我试图模拟这个库来监视faker.lorem.text()
的使用:
import * as faker from 'faker'
const mockFakerLoremText = jest.fn()
jest.mock('faker', () => ({
lorem: {
text: mockFakerLoremText
}
}))
it('should have called lorem.text() method', () => {
faker.lorem.text()
expect(mockFakerLoremText).toHaveBeenCalledTimes(1)
})
But then I got the following error:但后来我收到以下错误:
ReferenceError: Cannot access 'mockFakerLoremText' before initialization ReferenceError:在初始化之前无法访问“mockFakerLoremText”
So has someone an idea how I can spy on the call of this method .lorem.text()
?那么有人知道我如何监视这个方法.lorem.text()
的调用吗?
From the docs Calling jest.mock() with the module factory parameter来自文档Calling jest.mock() with the module factory parameter
A limitation with the factory parameter is that, since calls to
jest.mock()
are hoisted to the top of the file, it's not possible to first define a variable and then use it in the factory factory 参数的一个限制是,由于对jest.mock()
的调用被提升到文件的顶部,因此不可能先定义一个变量然后在工厂中使用它
That's why you got the error.这就是你得到错误的原因。
An working example using "jest": "^26.6.3"
:使用"jest": "^26.6.3"
的工作示例:
index.test.js
: index.test.js
:
import * as faker from 'faker';
jest.mock('faker', () => ({
lorem: {
text: jest.fn(),
},
}));
it('should have called lorem.text() method', () => {
faker.lorem.text();
expect(faker.lorem.text).toHaveBeenCalledTimes(1);
});
unit test result:单元测试结果:
PASS examples/65924623/index.test.ts
√ should have called lorem.text() method (3 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 0 | 0 | 0 | 0 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 6.913 s, estimated 7 s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.