繁体   English   中英

快递:我不知道如何使用sinon

[英]Express: I don't understand how to use sinon

我有一个控制器的方法:

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

我检查了我的USER数据是否进入控制器(req.user)。 我试图查看间谍中包含res的内容,但是找不到我不知道如何在我的情况下使用sinon的USER数据?

通过测试,您几乎做到了。 对于这种测试,我们可以使用calledWith从兴农检查功能和参数被正确调用。

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

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM