开玩笑+模拟实现+通话次数:0

时间:2019-12-10 06:26:24

标签: node.js jestjs

我正在使用Jest作为测试模块。开玩笑的间谍功能未调用,它显示为Number of calls: 0

a.test.js

 const request = require('request-promise');
    const moduleA = require('./a');
    test('Update function', async () => {
    const postSpy = jest.spyOn(request, 'post').mockImplementation((input) => input);
    await moduleA();
    expect(postSpy).toBeCalledWith({
    method: 'POST',
    uri:"fsdsfd",
    headers: {
     'content-type': 'application/json'
    },
    body: {
      A:A,
      B:B      
    },
    json: true 
});
    });

a.js

const request = require('request-promise');

module.exports = async () => {
  var options = {
    method: 'POST',
    uri: 'fsdsfd',
    headers: {
      'content-type': 'application/json',
    },
    body: {
      A: A,
      B: B,
    },
    json: true,
  };

  try {
    const selectResult = await request(options);
    return selectResult;
  } catch (err) {
    return err;
  }
};

它将引发错误,分别为expect(jest.fn()).toBeCalledWith(...expected)Number of calls: 0。我认为不调用模拟功能。我对此进行了很多搜索,但没有希望。有什么想法吗?

编辑

我的猜测是post中没有方法request-promise

编辑请求> POST()

    request.post({
      uri: 'fsdsfd',
      headers: {
        'content-type': 'application/json',
      },
      body: {
      A: A,
     B: B,
    },
    json: true,
    }, function(err, resp){
      if(err){
        console.log(err)
      } else {
        console.log(resp);
        return(resp)--------------->
      }
    });

ASYNC AWAIT EDIT

const ss = await request.post({
          uri: 'fsdsfd',
          headers: {
            'content-type': 'application/json',
          },
          body: {
          A: A,
         B: B,
        },
        json: true,
        });
return ss;

如果使用此选项,则不会调用箭头(->),因此不会在测试文件中分配它,因此我无法检查结果值。

1 个答案:

答案 0 :(得分:2)

您使用request(...)而不是request.post(...),因此需要模拟request函数而不是request.post方法。

例如 a.js

const request = require('request-promise');

module.exports = async () => {
  var options = {
    uri: 'fsdsfd',
    headers: {
      'content-type': 'application/json',
    },
    body: {
      A: 'A',
      B: 'B',
    },
    json: true,
  };

  try {
    const selectResult = await request.post(options);
    return selectResult;
  } catch (err) {
    return err;
  }
};

a.test.js

const request = require('request-promise');
const moduleA = require('./a');

jest.mock('request-promise', () => {
  return {
    post: jest.fn(),
  };
});

describe('59261385', () => {
  afterEach(() => {
    jest.resetAllMocks();
  });
  test('Update function', async () => {
    request.post.mockResolvedValueOnce({ result: [] });
    const actual = await moduleA();
    expect(actual).toEqual({ result: [] });
    expect(request.post).toBeCalledWith({
      uri: 'fsdsfd',
      headers: {
        'content-type': 'application/json',
      },
      body: {
        A: 'A',
        B: 'B',
      },
      json: true,
    });
  });
});

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

 PASS  src/stackoverflow/59261385/a.test.js (11.669s)
  59261385
    ✓ Update function (33ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |     87.5 |      100 |      100 |    83.33 |                   |
 a.js     |     87.5 |      100 |      100 |    83.33 |                20 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        13.599s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59261385

更新:

您也可以使用jest.spyOn

a.test.js

const request = require('request-promise');
const moduleA = require('../a');

describe('59261385', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  test('Update function', async () => {
    const postSpy = jest.spyOn(request, 'post').mockResolvedValueOnce({ result: [] });
    const actual = await moduleA();
    expect(actual).toEqual({ result: [] });
    expect(postSpy).toBeCalledWith({
      uri: 'fsdsfd',
      headers: {
        'content-type': 'application/json'
      },
      body: {
        A: 'A',
        B: 'B'
      },
      json: true
    });
  });
});

codesandbox:https://codesandbox.io/s/jestjs-jgye4