每次返回的锡农存根不同的价值

时间:2019-03-20 00:47:34

标签: javascript typescript mocha sinon

我对TypeScript / JavaScript相当陌生,但是我有一个很满意的VScode扩展名。我的问题是我的摩卡咖啡测试。我有以下功能

export async function getPackInfo (): Promise<IPackInfo> {
  let validChars = '^[0-9a-zA-Z-]+$'
  let ref
  ref = await getInput('Pack Reference (lowercase and (-) only)', 'pack-reference', 'my-first-pack')
  if (!ref.match(validChars)) {
    vscode.window.showErrorMessage('Pack name can only contain letters, numbers and dashes', 'Got it')
    return Promise.reject(new Error('Pack name can only contain letters, numbers and dashes. Pack will not be created correctly.'))
  }
  console.log(ref)
  let packname = ref.replace(/-/g, ' ').toLowerCase()
  .split(' ')
  .map((s) => s.charAt(0).toUpperCase() + s.substring(1))
  .join(' ')
  console.log(packname)
  let author
  if (getSetting('defaultAuthor')) {
    console.log('Got setting')
    author = getSetting('defaultAuthor')
  } else {
    console.log('Need input')
    author = await getInput('Pack Author', 'Pack Author', 'John Doe')
  }
  console.log(author)

  let email
  if (getSetting('defaultEmail')) {
    email = getSetting('defaultEmail')
  } else {
    email = await getInput('Author Email', 'Author Email', 'john@example.com')
  }
  console.log(email)
  if (!author || !email) {
    throw new Error('Pack author or email not defined')
  }
  // Write Pack Config File
  let data: IPackInfo = {
    'ref': ref,
    'packname': packname,
    'author': author,
    'email': email
  }
  return data
}

此函数调用另一个名为getInput的函数,该函数调用vscode.window.showInputBox:

export async function getInput (prompt: string, placeholder: string, defaultValue: string): Promise<string> {
  let value = await vscode.window.showInputBox({ prompt: prompt, placeHolder: placeholder, value: defaultValue }).then(function(value) {
    if (value) {
      resolve(value)
    }
    throw new Error('No value for prompt')
  })

我正在尝试测试数据是否在'getPackInfo'函数中正确返回。我的测试目前看起来像这样:

    it('Check that packname is converted correctly', function (done) {
      let mockGetInput
      mockGetInput = sinon.stub(vscode.window, 'showInputBox')
      mockGetInput.onFirstCall().resolves('ref-pack-here')
      mockGetInput.onSecondCall().resolves('Test Author')
      mockGetInput.onThirdCall().resolves('example@example.com')
      getPackInfo().then((res) => {
        let output = res['ref']
        console.log(`Output: ${res['packname']}`)
        console.log(`Output: ${res['author']}`)
        console.log(`Output: ${res['email']}`)
        console.log(`Output: ${res['ref']}`)
      }).catch(error => {
        console.log(error)
      })
      done()
      mockGetInput.restore()
    })

我现在已经待了好几天了,但是我无法让每个电话都具有不同的价值!

第一个调用正确返回,但所有后续调用均不返回任何内容。

如果有更好的方法,我很乐于尝试!

1 个答案:

答案 0 :(得分:0)

您似乎需要对import React from 'react'; import Airtable from "airtable"; const base = new Airtable({ apiKey: "API_KEY" }).base( "BASE_ID" ); let i = 0; export default class Component1 extends React.Component { constructor(props) { super(props); this.state = { content: '', records: '', slug: '', }; } componentDidMount() { this.getRecords() } getRecords = () => { base("BASE_NAME") .select({ view: "Grid view" }) .eachPage((records, fetchNextPage) => { this.setState({ records }, () => this.parseRecord(i)); fetchNextPage(); }); } parseRecord = i => { const product = this.state.records[i].fields; this.setState({ content: product.Content slug: product.Slug }); }; onClickNext = () => { i < this.state.records.length - 2 ? i++ : (i = 0); this.parseRecord(i); }; render() { return ( <div> <img src={this.state.content} onClick={onClickNext} /> </div> ) } 代码进行一些修复。


现在async 始终解析为getInputundefinedresolve子句中是未定义的,因此then总是会拒绝并出现错误,但是即使该问题不存在,将要发生的Promise 否则将不会返回value

您可以通过将其更改为以下内容来解决这些问题:

vscode.window.showInputBox

您正在正确地创建模拟,只需要等待export async function getInput (prompt: string, placeholder: string, defaultValue: string): Promise<string> { const value = await vscode.window.showInputBox({ prompt: prompt, placeHolder: placeholder, value: defaultValue }); if (value) { return value; } throw new Error('No value for prompt') } 返回的Promise解析之后,即可恢复模拟并结束测试。

现在,它正在调用getPackInfo,然后立即调用getPackInfo,还原模拟,并在done中的任何async代码甚至没有完成之前结束测试跑步的机会。

最简单的解决方法是使用getPackInfo测试函数并在async上调用await

Promise