Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Jest单元测试&x2B;接收未定义_Javascript_Node.js_Unit Testing_Jestjs - Fatal编程技术网

Javascript Jest单元测试&x2B;接收未定义

Javascript Jest单元测试&x2B;接收未定义,javascript,node.js,unit-testing,jestjs,Javascript,Node.js,Unit Testing,Jestjs,我使用Jest作为我的单元测试框架。我试图模拟第三方npm“请求”并执行我的测试用例,但是我收到了,测试失败了 expect(jest.fn()).toHaveBeenCalledWith(...expected) Expected: 200 Number of calls: 0 以下是我的代码: spec.js jest.mock('request', () => ({ post: jest.fn() })); const request = require('

我使用Jest作为我的单元测试框架。我试图模拟第三方npm“请求”并执行我的测试用例,但是我收到了,测试失败了

expect(jest.fn()).toHaveBeenCalledWith(...expected)

    Expected: 200

    Number of calls: 0
以下是我的代码:

spec.js

jest.mock('request', () => ({
  post: jest.fn()
}));
const request = require('request');

const mockRequest = (reqData) => {
    return {
      params: reqData.params? reqData.params:{} ,
      body: reqData.body?reqData.body:{},
      headers: reqData.headers?reqData.headers:{}
    };
  };

  const mockResponse = () => {
    const res = {};
    res.status = jest.fn().mockReturnValue(res);
    res.json = jest.fn().mockReturnValue(res);
    res.send = jest.fn().mockReturnValue(res);
    return res;
  };
  describe("Test suite for controller", () => {   
    test("should return true for successful validation",async () => {
request.post.mockResolvedValue({
        "key1":"value1",
        "key2":"value2"
      });
 const req = mockRequest();
      const res = mockResponse();
      const Ctrl = require('../../controllers/ctrl')
      await Ctrl.validate(req, res);
      //const result = await res1.json();
      expect(res.status).toHaveBeenCalledWith(200); 
});
});
const request = require('request');
module.exports = {
  async validate(req, res) {
      var postBody = {
        url: url,
        form: body,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      };      

      await request.post(postBody, function (error, response, body) { 
        if (error) {
           return res.status(200).json({ result: "false" });
        } else {
            return res.status(200).json({ result: "true" });
        }
     });
});
}
Ctrl.js

jest.mock('request', () => ({
  post: jest.fn()
}));
const request = require('request');

const mockRequest = (reqData) => {
    return {
      params: reqData.params? reqData.params:{} ,
      body: reqData.body?reqData.body:{},
      headers: reqData.headers?reqData.headers:{}
    };
  };

  const mockResponse = () => {
    const res = {};
    res.status = jest.fn().mockReturnValue(res);
    res.json = jest.fn().mockReturnValue(res);
    res.send = jest.fn().mockReturnValue(res);
    return res;
  };
  describe("Test suite for controller", () => {   
    test("should return true for successful validation",async () => {
request.post.mockResolvedValue({
        "key1":"value1",
        "key2":"value2"
      });
 const req = mockRequest();
      const res = mockResponse();
      const Ctrl = require('../../controllers/ctrl')
      await Ctrl.validate(req, res);
      //const result = await res1.json();
      expect(res.status).toHaveBeenCalledWith(200); 
});
});
const request = require('request');
module.exports = {
  async validate(req, res) {
      var postBody = {
        url: url,
        form: body,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      };      

      await request.post(postBody, function (error, response, body) { 
        if (error) {
           return res.status(200).json({ result: "false" });
        } else {
            return res.status(200).json({ result: "true" });
        }
     });
});
}
请分享你的想法。谢谢你

  • 您不需要将
    wait
    request的回调一起使用。post
    ,只需选择其中一个。不要同时使用它们。选择Promise或error first回调来处理异步代码
  • 您应该模拟
    request.post的实现,以便在测试用例中获得回调函数。然后,您可以将成功的响应或错误传递到此回调,并测试回调的代码逻辑
  • 您可以使用模拟
    res
    对象的链方法
  • 以下是单元测试解决方案:

    ctrl.js

    const request=require('request');
    module.exports={
    异步验证(req、res){
    var postBody={
    url:'url',
    表格:要求正文,
    标题:{
    “内容类型”:“应用程序/x-www-form-urlencoded”,
    },
    };
    post(postBody,函数(错误,响应,body){
    如果(错误){
    返回res.status(200).json({result:'false'});
    }否则{
    返回res.status(200).json({result:'true'});
    }
    });
    },
    };
    
    ctrl.spec.js

    const request=require('request');
    常量Ctrl=require('./Ctrl');
    jest.mock('request',()=>({
    post:jest.fn(),
    }));
    描述('控制器测试套件',()=>{
    毕竟(()=>{
    jest.resetAllMocks();
    });
    test('验证成功时应返回true',async()=>{
    request.post.mockImplementationOnce((主体,回调)=>{
    回调(空);
    });
    const req={body:{}};
    const res={status:jest.fn().mockReturnThis(),json:jest.fn()};
    等待Ctrl.validate(请求、恢复);
    expect(request.post).toBeCalledWith(
    {
    url:'url',
    表格:{},
    标题:{
    “内容类型”:“应用程序/x-www-form-urlencoded”,
    },
    },
    expect.any(函数),
    );
    期望(物质状态)。与(200)一起被收集;
    expect(res.json).toBeCalledWith({result:'true'});
    });
    测试('应处理验证失败的错误',异步()=>{
    const mErr=新错误(“网络”);
    request.post.mockImplementationOnce((主体,回调)=>{
    回调(mErr);
    });
    const req={body:{}};
    const res={status:jest.fn().mockReturnThis(),json:jest.fn()};
    等待Ctrl.validate(请求、恢复);
    expect(request.post).toBeCalledWith(
    {
    url:'url',
    表格:{},
    标题:{
    “内容类型”:“应用程序/x-www-form-urlencoded”,
    },
    },
    expect.any(函数),
    );
    期望(物质状态)。与(200)一起被收集;
    expect(res.json).toBeCalledWith({result:'false'});
    });
    });
    
    单元测试结果和覆盖率报告:

     PASS  src/stackoverflow/64311760/ctrl.spec.js (16.499s)
      Test suite for controller
        ✓ should return true for successful validation (16ms)
        ✓ should handle error for failed validation (2ms)
    
    ----------|----------|----------|----------|----------|-------------------|
    File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
    ----------|----------|----------|----------|----------|-------------------|
    All files |      100 |      100 |      100 |      100 |                   |
     ctrl.js  |      100 |      100 |      100 |      100 |                   |
    ----------|----------|----------|----------|----------|-------------------|
    Test Suites: 1 passed, 1 total
    Tests:       2 passed, 2 total
    Snapshots:   0 total
    Time:        19.59s
    

    谢谢你的回答。你能解释一下这些变化吗??。那么,我实现了什么?@Subburaj更新了答案。