如何使用玩笑和打字稿在另一个函数中测试函数

时间:2020-07-27 21:24:22

标签: node.js typescript jestjs

我必须测试processMsg。但是,它没有被调用。以下是我尝试的代码:

userdata.ts

int cont=0;

for(i=0; i<10;i++){
  if(numbers[i]==number){
    System.out.println("I found it");
    cont++;
    break;
  }
}
if(cont==0)
  System.out.println("That number is not in the array!");

test.ts

import { listen } from './rdkafka';
export class UserData {
    unsubscribe: any;
    config: any;

    constructor() {
        this.config = {
           name: 'msgHandler'
        }
    };
    private processMsg = (value): void => {
        console.log('param value', value.toString());
        this.unsubscribe();
    };
    getData = (): void => {
        this.unsubscribe = listen({
            name: this.config.name,
            processMessage: this.processMsg
        });
    };
}

listen.ts

describe('UserData', () => {
    let userData: UserData;
    beforeEach(() => {
        userData = new UserData();
    });
    it('userData', () => {
        expect(userData.getData()).toBeUndefined();
    })
})

getData方法已成功测试,但需要在getData中测试侦听方法。任何帮助都会非常有帮助

1 个答案:

答案 0 :(得分:0)

您可以使用jest.mock(moduleName, factory, options)模拟./rdkafka模块,listen函数及其实现。然后,您可以根据传递给processMsg函数的对象在测试用例中获取原始的私有方法listen。之后,您可以测试processMsg方法。下面是单元测试解决方案:

例如

userdata.ts

import { listen } from './rdkafka';

export class UserData {
  unsubscribe: any;
  config: any;

  constructor() {
    this.config = {
      name: 'msgHandler',
    };
  }
  private processMsg = (value): void => {
    console.log('param value', value.toString());
    this.unsubscribe();
  };
  getData = (): void => {
    this.unsubscribe = listen({
      name: this.config.name,
      processMessage: this.processMsg,
    });
  };
}

rdkafka.ts

export const listen = (opts) => {
  console.log('real implementation');
};

userdata.test.ts

import { UserData } from './userdata';
import { listen } from './rdkafka';
import { mocked } from 'ts-jest/utils';

jest.mock('./rdkafka');

describe('63123784', () => {
  let userData: UserData;
  beforeEach(() => {
    userData = new UserData();
  });
  afterAll(() => {
    jest.resetAllMocks();
  });
  it('should pass', () => {
    expect(jest.isMockFunction(listen)).toBeTruthy();
    expect(userData.getData()).toBeUndefined();
  });
  it('should process message', () => {
    let processMessageRef;
    const mUnsubscribe = jest.fn();
    mocked(listen).mockImplementationOnce((opts) => {
      processMessageRef = opts.processMessage;
      return mUnsubscribe;
    });
    const logSpy = jest.spyOn(console, 'log');
    userData.getData();
    processMessageRef(1);
    expect(listen).toBeCalledWith({ name: 'msgHandler', processMessage: processMessageRef });
    expect(mUnsubscribe).toBeCalledTimes(1);
    expect(logSpy).toBeCalledWith('param value', '1');
  });
});

具有覆盖率报告的单元测试结果:

 PASS  stackoverflow/63123784/userdata.test.ts (9.673s)
  63123784
    ✓ should pass (3ms)
    ✓ should process message (26ms)

  console.log
    param value 1

      at CustomConsole.<anonymous> (node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866:25)

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------|---------|----------|---------|---------|-------------------
All files    |   92.31 |      100 |      80 |   91.67 |                   
 rdkafka.ts  |      50 |      100 |       0 |      50 | 2                 
 userdata.ts |     100 |      100 |     100 |     100 |                   
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        10.946s