[英]How to spyOn an exported standalone function using javascript jest?
這是一個非常簡單的場景,但我一直在努力尋找答案。
助手.ts:
export function foo() {
bar();
}
export function bar() {
// do something
}
helpers.spec.ts:
import { foo, bar } from "./helpers";
describe("tests", () => {
it("example test", () => {
const barSpy = // how can i set this up?
foo();
expect(barSpy).toHaveBeenCalled();
});
});
我不能做const spy = jest.spyOn(baz, 'bar');
因為我沒有一個模塊/類來代替“baz”。 它只是一個出口的 function。
編輯: Jest mock 內部 function已被建議為重復但不幸的是它對我的場景沒有幫助。
該問題的解決方案:
移至單獨的模塊:我無法為我的場景執行此操作。 如果我在我的應用程序中測試每個 function,這將導致我創建 10 個不理想的新文件。 (澄清一下,我認為這個解決方案可以工作,但我不能在我的場景中使用它。我已經是 mocking 一個單獨的文件 function 在這個測試文件中成功。)
將模塊導入自身:
helpers.spec.ts:
import * as helpers from "./helpers";
describe("tests", () => {
it("example test", () => {
const barSpy = jest.spyOn(helpers, 'bar');
foo();
expect(barSpy).toHaveBeenCalled();
});
});
結果是:
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
這是封閉的解決方案:
export function bar() {
// do something
}
export function foo() {
exports.bar(); // <-- have to change to exports.bar() instead of bar()
// or this.bar(); would also work.
}
import * as utils from './utils';
describe('tests', () => {
it('example test', () => {
const barSpy = jest.spyOn(utils, 'bar');
utils.foo();
expect(barSpy).toHaveBeenCalled();
});
});
或者看看這個重復的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.