簡體   English   中英

如何使用 jest 模擬在回調函數中發回的結果

[英]How to use jest to mock the results being sent back in the callback functions

有沒有辦法模擬storage對象,以便我可以在執行storage.get時控制回調函數中傳回的errv

const mod = (() => {
  let value;

  return {
    init: (storage) => {
      storage.get('key', (err, v) => {
        value = v;
      });
    },
    get: () => value
  };
})();

由於我關心storage.get副作用,我不能簡單地執行mockImplementation來覆蓋該函數。 那是對的嗎?

創建一個mod.init storage對象並將其傳遞給mod.init方法。

例如

index.ts

const mod = (() => {
  let value;

  return {
    init: (storage) => {
      storage.get('key', (err, v) => {
        value = v;
      });
    },
    get: () => value,
  };
})();

export { mod };

index.test.ts

import { mod } from './';

describe('63640360', () => {
  it('should pass', () => {
    const mStorage = {
      get: jest.fn().mockImplementationOnce((key, callback) => {
        callback(null, 'teresa teng');
      }),
    };
    mod.init(mStorage);
    const actual = mod.get();
    expect(actual).toBe('teresa teng');
    expect(mStorage.get).toBeCalledWith('key', expect.any(Function));
  });
});

帶有覆蓋率報告的單元測試結果:

 PASS  src/stackoverflow/63640360/index.test.ts
  63640360
    ✓ should pass (5ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.079s, estimated 9s

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM