Sinon 存根返回先前测试用例的模拟值

问题描述

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

我正在尝试从我已实现的方法中测试一个函数,该函数应该基于某些中间函数的返回有 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,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
  }
}

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

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

非常感谢。

解决方法

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

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

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...