单元测试Web3 Angular 6

时间:2018-10-15 17:31:53

标签: unit-testing angular6 web3

我正在尝试对在Angular 6中完成的web3服务进行自动测试。我对这种测试是陌生的,对于web3库来说是新的。

服务:

import { Injectable, InjectionToken, Inject } from '@angular/core';
import Web3 from 'web3';

declare let require: any;
const buttonABI = require('../../assets/abi/Button.json');

export const WEB3 = new InjectionToken<Web3>('web3', {
  providedIn: 'root',
  factory: () => {
    if (Web3) {
      const resp = new Web3(Web3.givenProvider || 'http://localhost:7545');
      return resp;
    } else {
      console.log('No web3? You should consider trying MetaMask!');
    }
  }
});

@Injectable({
  providedIn: 'root'
})
export class CoreService {
  private account = null;

  constructor(@Inject(WEB3) private web3: any, private http: Http) {
  }

  public async getAccount() {
    if (this.account === null) {
      return (await this.web3.eth.getAccounts())[0];
    }
  }
}

测试:

describe('AppComponent', () => {
  let service: any;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [HttpClientTestingModule, HttpModule],
      providers: [CoreService, { provide: XHRBackend, useClass: MockBackend }]
    }).compileComponents();

    service = new CoreService(
      new Web3(Web3.givenProvider || 'http://localhost:7545'),
      null
    );
  }));

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

  it('should get first account', () => {
    console.log(service);
    service
      .getAccount()
      .then(resp => {
        console.log(resp);
        // expect(resp).toBe(1);
      })
      .catch(err => {
        console.log(err);
      });
  });

在此行:

new Web3(Web3.givenProvider || 'http://localhost:7545')

第二个参数是Ganache实例,该实例将毫无问题地进行连接,但是如果我删除该参数并强制其使用Web3.givenProvider来连接到Metamask和Rinkeby,我总是会得到null。

在网络上找不到任何示例。

您对此有任何暗示吗?提前非常感谢!

0 个答案:

没有答案