微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我正在尝试使用 Sinon 存根和模拟来测试我的函数,但出现错误请建议我正确的写作技巧

如何解决我正在尝试使用 Sinon 存根和模拟来测试我的函数,但出现错误请建议我正确的写作技巧

在这个模块中,我想测试调用其他模块的 findAll 函数的 searchAll 函数,所以我试图存根其他模块的 findAll 函数并模拟我的 test.js 模块中的 res。

UseControllerModule.js

exports.searchAll = (req,res) => {
    Users.findAll((err,data) => {
        if (err)
            res.status(500).send({
                message: err.message || "Some error occured while retrieving data",});
        else res.send(data);
    });
};

一个模块的 findAll 函数一个 userid 参数被存根。

所以在存根并获得响应值之后,我试图在这里模拟响应,但它没有运行。模拟验证导致错误。如果我删除验证,测试用例会通过,但不会增加任何测试覆盖率。

Test.js

describe("searchAll",function() {
    let res;

    beforeEach(() => {
        res = {
            json: function() {},};
    });

    it("should return all the id's of  members of the club",async function() {
        const stubvalue = {
            userid: faker.random.uuid(),};
        const mock = sinon.mock(res);
        mock.expects("json").withExactArgs({
            data: stubValue
        });

        const stub = sinon.stub(usermodel,"findAll").returns(Stubvalue);
        const user = await UserController.searchAll();
        expect(stub.calledOnce).to.be.true;
        mock.verify();
        stub.restore();

    });
});

解决方法

您应该使用 stub.callsFake(fakeFunction);UserModel.findAll() 方法提供虚假实现。它接受一个回调参数,因此您需要执行它并手动将 stubvalue 传递给您的假实现中的该回调。

UseControllerModule.js

const Users = require('./UserModel');

exports.searchAll = (req,res) => {
  Users.findAll((err,data) => {
    if (err) {
      res.status(500).send({
        message: err.message || 'Some error occured while retrieving data',});
    } else {
      res.send(data);
    }
  });
};

UserModel.js

module.exports = {
  findAll(callback) {
    console.log('real implementation');
    callback(null,'real data');
  },};

UseControllerModule.test.js

const sinon = require('sinon');
const { expect } = require('chai');
const UserModel = require('./UserModel');
const UserController = require('./UseControllerModule');

describe('searchAll',function () {
  let res;

  beforeEach(() => {
    res = {
      send: function () {},};
  });

  it("should return all the id's of  members of the club",async function () {
    const stubvalue = {
      userid: '123',};
    const mock = sinon.mock(res);
    mock.expects('send').withExactArgs(stubvalue);

    const stub = sinon.stub(UserModel,'findAll').callsFake((callback) => {
      callback(null,stubvalue);
    });
    UserController.searchAll({},res);
    expect(stub.calledOnce).to.be.true;
    mock.verify();
    stub.restore();
  });
});

单元测试结果:

  searchAll
    ✓ should return all the id's of  members of the club


  1 passing (6ms)

------------------------|---------|----------|---------|---------|-------------------
File                    | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------------------|---------|----------|---------|---------|-------------------
All files               |   66.67 |       25 |   66.67 |   66.67 |                   
 UseControllerModule.js |   83.33 |       25 |     100 |   83.33 | 6                 
 UserModel.js           |   33.33 |      100 |       0 |   33.33 | 3-4               
------------------------|---------|----------|---------|---------|-------------------

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?