如何模拟回调

时间:2019-12-17 09:44:45

标签: javascript jestjs

我想测试我的函数,它的末尾有这样的回调:

const authorizer = (event, context, callback) => {

    const token = event.authorizationToken;
    try {
        {...}
        callback(null, policyDocument)
    } catch (e) {
        callback('Unauthorized');
    }

};

但是当我尝试用笑话来测试它时,它会返回“回调不是函数”。所以我想知道如何在最后模拟嘲笑以及如何在我的jest文件中调用它。

PS:我的授权者测试部分如下所示:

describe('authorizer', () => {
    let mockCallback, var1, var2, var3, event;

    beforeEach(async() => {
        mockCallback = jest.fn().mockReturnValue('ok')
        var 1 ='...'
        var 2 ='...'
        var 3 ='...'
        event = '...'
        actualValue = await authorize.authorizer(event, null, mockCallback)
    })

    it('should authorize', async () => {
        expect(actualValue).toHaveBeenCalled()
    })
})

响应:

Matcher error: received value must be a mock or spy function

    Received has value: undefined

1 个答案:

答案 0 :(得分:0)

这是解决方案:

index.ts

export const authorizer = (event, context, callback) => {
  const token = event.authorizationToken;
  const policyDocument = {};
  try {
    callback(null, policyDocument);
  } catch (e) {
    callback('Unauthorized');
  }
};

index.spec.ts

import { authorizer } from './';

describe('authorizer', () => {
  it('should authorize', () => {
    const event = 'message';
    const mockCallback = jest.fn().mockReturnValue('ok');
    authorizer(event, null, mockCallback);
    expect(mockCallback).toHaveBeenCalled();
  });
});

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

 PASS  src/stackoverflow/59371450/index.spec.ts (10.989s)
  authorizer
    ✓ should authorize (5ms)

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