代码之家  ›  专栏  ›  技术社区  ›  Subburaj

Jest+mockImplementation+调用数:0

  •  0
  • Subburaj  · 技术社区  · 6 年前

    Jest 作为测试模块。它说,没有调用Jest spy函数 Number of calls: 0 .

    答。测试.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) 和 呼叫数:0 . 我认为没有调用mock函数。关于这个我找了很多,但没有希望。有什么想法吗??

    编辑

    post request-promise .

    编辑请求>发布()

        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)--------------->
          }
        });
    

    异步等待编辑

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

    在这里,如果您使用这个箭头(-->)不会被调用,所以它不会在测试文件中赋值,所以我无法检查结果值。

    0 回复  |  直到 6 年前
        1
  •  2
  •   Lin Du Correcter    6 年前

    你用 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

    答。测试.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
        });
      });
    });
    

    代码沙盒: https://codesandbox.io/s/jestjs-jgye4