简体   繁体   English

如何使用 jest 模拟在回调函数中发回的结果

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

Is there a way to mock the storage object so I can control the err and v passed back in the callback function when I do storage.get ?有没有办法模拟storage对象,以便我可以在执行storage.get时控制回调函数中传回的errv

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

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

Since I care about the side effects of storage.get I cannot simply do mockImplementation to override the function.由于我关心storage.get副作用,我不能简单地执行mockImplementation来覆盖该函数。 is that correct?那是对的吗?

Create a mocked storage object and pass it into mod.init method.创建一个mod.init storage对象并将其传递给mod.init方法。

Eg例如

index.ts : index.ts

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

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

export { mod };

index.test.ts : 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));
  });
});

unit test result with coverage report:带有覆盖率报告的单元测试结果:

 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