【问题标题】:Sinon stub returning the mocked value of previous test caseSinon 存根返回先前测试用例的模拟值
【发布时间】:2021-04-02 22:23:26
【问题描述】:

我遇到了一个让我发疯的问题。

我正在尝试从我已实现的方法中测试一个函数,该方法应该基于一些中间函数的返回有 2 种不同的结果。所以,我使用 sinon 来模拟一个中间函数返回值(实际上它会调用一个 API),但问题是对于第一个测试,模拟结果是正确的,但在第二个结果中,我指定的结果保持不变第一个,而不是我正在尝试做的新模拟。

我在 afterEach 中恢复模拟,但它仍然无法正常工作。

我的代码如下:

import * as exportedFuncs from './src/utilFuncs';

import assert from 'assert';
import sinon from 'sinon';

describe('Utils', () => {
  let mock: any;
  beforeEach(function() {
    mock = sinon.stub(exportedFuncs, 'setDefault');
  });

  afterEach(function() {
    mock.restore();
  });

  it('Func should return a default prop', async () => {
    const mockedRequest = {
      hostname: 'www.example.com'
    };
    const ctx = { req: mockedRequest, userName: 'test', password: 'someLongPass12345$$' };

    mock.returns(
      Promise.resolve({
          code: 'test'
        })
    );
    
    const result = await exportedFuncs.buildInfo(ctx);

    let code = result?.defaultValue?.code;

    assert('defaultValue' in result);
    assert.strictEqual(code, 'test');
  });

  it('Func should return a redirectUrl', async () => {
    const mockedRequest = {
      hostname: 'www.example.com'
    };

    const ctx = { req: mockedRequest, userName: 'test', password: 'someLongPass12345$$' };

    mock.returns(Promise.resolve(null));

    sinon.stub(exportedFuncs, 'getRedirect').returns(
      Promise.resolve({
         toUrl: 'www.sample-redirect.com',
         statusCode: 302
       })
    );

    const result = await exportedFuncs.buildInfo(pipelineContext);
    console.log('result',result);

    // the properties have different names because they're parsed by another internal function
    const { redirectStatusCode, redirectUrl } = result.redirect;

    assert.strictEqual(redirectUrl, 'www.sample-redirect.com');
    assert.strictEqual(redirectStatusCode, 302);
  });
});

我在这些测试中得到的结果是第一个按预期通过,但第二个失败并且 console.log 显示:

{
  defaultValue: {
    code: 'test'
  },
  redirect: null
}

这是模拟后第一个测试用例的预期结果。我期待它返回的是:

{
  defaultValue: null,
  redirect: {
    redirectUrl: 'www.sample-redirect.com',
    redirectStatusCode: 302
  }
}

另外,如果我注释第一个测试用例并只运行第二个,测试通过。

你们能告诉我我在这里做错了什么吗?

非常感谢。

【问题讨论】:

    标签: javascript typescript unit-testing sinon


    【解决方案1】:

    您需要使用this.mock 声明和引用该变量,而不是将其声明为闭包 (let mock: any)

    异步测试并行运行,两个测试同时访问同一个变量。这就是您看到这种行为的原因。

    请确保在您的测试函数中使用 function() { ... } 而不是 () => { ... } 语法,否则它将无法按预期工作。

    【讨论】:

    • 谢谢,这完全有道理...我会在星期一尝试一下,看看它是否有效,然后标记答案。
    猜你喜欢
    • 2015-11-28
    • 2017-02-04
    • 1970-01-01
    • 2021-12-10
    • 2019-08-25
    • 2014-04-02
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多