javascript - express : I don't understand how to use sinon

标签 javascript unit-testing sinon sinon-chai

我有一个带有方法的 Controller :

registration(req, res) {
  if (!req.user) return res.status(401).send('Registration failed');

  const { user } = req;
  return res.status(201).json({ user });
},

我想测试使用我的假数据发送 json 的注册方法。

const { expect } = require('chai');
const sinon = require('sinon');
const authController = require(...);

describe('authController', () => {
  const USER = {
  email: 'test@test.com',
  password: 'Test12345',
  confirm: 'Test12345',
  username: 'Test',
};

it('it should send user data with email: test@test.com', () => {
  const req = { user: USER };
  const res = {
    status: sinon.stub().returnsThis(),
    json: sinon.spy(),
  };

  console.log('RES: ', res); // I can't see the json data
  authController.registration(req, res);
  expect(res.json).to.equal(USER);
});

我检查了我的用户数据是否进入 Controller (req.user)。 我试图用 spy 查看包含 res 的内容,但没有找到我的用户数据 我不明白如何在我的情况下使用 sinon ?

最佳答案

你几乎通过了测试。对于这种测试,我们可以使用Sinon的usedWith来检查函数和参数是否被正确调用。

describe('authController', () => {
  const USER = {
    email: 'test@test.com',
    password: 'Test12345',
    confirm: 'Test12345',
    username: 'Test',
  };

  it('it should send user data with email: test@test.com', () => {
    const req = { user: USER };
    const res = {
      status: sinon.stub().returnsThis(),
      json: sinon.spy(),
    };

    authController.registration(req, res);

    // this is how we check that the res is being called with correct arguments
    expect(res.status.calledWith(201)).to.be.ok;
    expect(res.json.calledWith({ user: USER })).to.be.ok;
  });
});

希望有帮助。

关于javascript - express : I don't understand how to use sinon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51370338/

相关文章:

unit-testing - 我可以在没有 TestScheduler 的情况下对 RxJS 函数进行单元测试吗?

javascript - 将 HTML 列表项更改为在导航栏中处于事件状态

wpf - 如何模拟 DragEventArgs

java - Java 新手——返回单元测试失败

c# - 将当前的单元测试结果与之前的进行比较

node.js - 使用 mocha 和 sinon 在 Node 中模拟 http 请求

angularjs - 替换 sinon stub 中的多个方法

javascript - 从 JavaScript 控制台查找和操作 React.js 组件

javascript - amMap 删除主页按钮控件

javascript - 如何从 JISON 解析器中获取抽象语法树 (AST)?