简体   繁体   中英

Unit testing in Typescript with Dependency Injection using Inversify with mocha and chai

I created typescript project using inversify and unit tests using mocha and chai.

@injectable()
export class SomeClass{

// Used in Constructor injection
readonly object1:TypeObjectClass; 

// Property Injection 
(@inject(TYPE2)
readonly someObject1:TypeSomeObjectClass1; 

constructor(@inject(TYPE) object1: TypeObjectClass) {

this.object1=object1

}

public someMethod(){

this.object1.DoSomething();
this.someObject1.DoAnything();

}
}

I wrote a unit test for the above class

Unit Test

let chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
let expect = chai.expect;

describe('Test Interaction Controller APIs', () => {

 let object1: IMock<TypeObjectClass>;
 let someObject: IMock<TypeSomeObjectClass1>;
let someClass: SomeClass;

beforeEach(()=>{
//Mock objects
 object1= Mock.ofType<object1>();
 someObject= Mock.ofType<TypeSomeObjectClass1>();
// Constructor injected. 
SomeClass=new SomeClass(object1.object)

})

}

How do I inject someObject1 in my unit test since this is property injection?

You can create a snapshot of your container and rebind any values to your mocks.

import container from "path_to_your_container";

describe("Intent Logic Handler Test", () => {

  beforeEach(() => {
    container.snapshot();
  });

  afterEach(() => {
    container.restore();
  });

  test("Your test", () => {

    // Arrange

    const mock= TypeMoq.Mock.ofType<IFoo>();
    container.rebind("Object").toConstantValue(mock.object);

    const sut = new Foo();

    // Assert
    assert.throws(() => {
      sut.handle(turn);
    }, Error, "Name cannot be undefined.");
  });

More info can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM