【问题标题】:Testing promise with stub使用存根测试 Promise
【发布时间】:2021-05-21 20:28:33
【问题描述】:

我正在尝试使用 sinon 存根对 chai 进行一些测试。问题是,我正在像这样存根我的 fetch 并履行我的诺言。

  let fetchedStub;

  beforeEach(() => {
    fetchedStub = sinon.stub(global, 'fetch');
    fetchedStub.resolves({ json: () => { body: 'json' } });
  });

然后我正在测试我的数据是否正确返回

it('should return the JSON data from the promise', () => {
  const result = search('test');
  result.then((data) => {
    expect(data).to.be.eql({ body: 'json' });
  });
});

但我没有通过测试,而是得到了

TypeError: Cannot read property 'then' of undefined

我的承诺做错了吗?我想我需要一些光。

编辑:这是搜索功能。

    export const search = (query) => {
  fetch(`https://api.spotify.com/v1/search?q=${query}&type=artist`)
    .then(data => data.json());
};

【问题讨论】:

  • 请出示search函数的代码
  • 问题就在那里

标签: node.js chai sinon stub sinon-chai


【解决方案1】:

您的 search 箭头函数不返回任何内容,因此在您的测试中 result 未定义,因此出现错误消息。

你应该简单地返回你获取的结果:

export const search = (query) => {
  // return something
  return fetch(`url`).then(data => data.json());
};

可能被箭头函数简写语法弄糊涂了,它会自动返回单个表达式的结果,前提是它不是 用花括号括起来:

export const search = (query) => fetch(`url`).then(data => data.json()); // no curly braces after the arrow

【讨论】:

  • 谢谢你,对我帮助很大
猜你喜欢
  • 1970-01-01
  • 2017-06-05
  • 2013-11-12
  • 2017-04-08
  • 2020-04-21
  • 1970-01-01
  • 1970-01-01
  • 2013-02-10
  • 2018-03-24
相关资源
最近更新 更多