NodeJS 如何使用sinon(或其他东西)检查es6ts类是否是用参数创建的

kx5bkwkv  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(91)

假设我在Node.js的typescript中使用auth0
我想测试这个类:
ClassToTest.ts

import { AuthenticationClient, AuthenticationClientOptions } from 'auth0';

export class ClassToTest {
    public static getClient(): AuthenticationClient {
        let options = {
            domain: global.myConfig.DOMAIN,
            clientId: global.myConfig.CLIENT,
            clientSecret: global.myConfig.SECRET
        } as AuthenticationClientOptions;
        let auth0 = new AuthenticationClient(options);

        return auth0;
    }
}

export default ClassToTest;

现在我想写一个单元测试,确认正确的值被传递到options
我正在尝试像

import { expect } from "chai";
import * as sinon from 'sinon';

import ClassToTest from "./ClassToTest";
import { AuthenticationClient, AuthenticationClientOptions } from "auth0";

describe("ClassToTest", () => {
    beforeEach(() => {
       global.myConfig.DOMAIN = 'someValue';
    });
    
    afterEach(() => {
        sinon.restore();
    });

    it("uses right options", async function () {
        let usedOptions: AuthenticationClientOptions;
        sinon.stub(AuthenticationClient.prototype, 'constructor')
            .callsFake((opts: AuthenticationClientOptions) => {
                usedOptions = opts;
            });
        expect(usedOptions.domain).to.equal('someValue');
    });
})

这给了我:
错误TS2345:“constructor”类型的参数不能分配给“keyof AuthenticationClient”类型的参数。

gudnpqoy

gudnpqoy1#

我们不能像这样stub JS类的constructor,参见issues/1892
一种解决方案是使用proxyquire来消除auth0模块及其AuthenticationClient类。此外,我们可以使用.getCall(n).args来获取第n次调用的存根参数。
例如
classToTest.ts

import { AuthenticationClient } from './auth0';

export class ClassToTest {
  public static getClient(): AuthenticationClient {
    let options = {
      domain: global.myConfig.DOMAIN,
      clientId: global.myConfig.CLIENT,
      clientSecret: global.myConfig.SECRET,
    };
    let auth0 = new AuthenticationClient(options);

    return auth0;
  }
}

export default ClassToTest;

auth0.ts

// Simulate auth0 module
export class AuthenticationClient {
  constructor(options) {}
}

classToTest.test.ts

import proxyquire from 'proxyquire';
import sinon from 'sinon';

describe('76519308', () => {
  beforeEach(() => {
    global.myConfig = global.myConfig || {};
    global.myConfig.DOMAIN = 'someValue';
  });

  it('should pass', () => {
    const AuthenticationClientStub = sinon.stub();
    const ClassToTest = proxyquire('./classToTest', {
      './auth0': {
        AuthenticationClient: AuthenticationClientStub,
      },
    }).default;
    ClassToTest.getClient();
    sinon.assert.match(AuthenticationClientStub.getCall(0).args[0].domain, 'someValue');
  });
});

相关问题